How to get list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM

Home | Office 365 | How to get list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM

In this post, we’ll see how we can get the list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM. I’ll be using a Console application for the purpose of demonstration.

Open Visual Studio 2013.

File –> New Project –> Visual C# –> Console Application and name it as ‘GetFieldsCSOM’

Add a reference to the ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’ assemblies

Import the following namespaces

using Microsoft.SharePoint.Client;
using System.Security;

The following code will invoke the GetbyTitle method of Lists class and access the Fields property collection.

namespace GetFieldsCSOM
{
    class Program
    {
        
        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

        static void Main(string[] args)
        {
            //Replace it with the url of your tenant or your site-collection
            string SiteUrl = "https://yoursite.sharepoint.com";
            System.Uri oUri = new System.Uri(SiteUrl);
            using (ClientContext oClientContext = new ClientContext(SiteUrl))
            {
                //Replace it with your user id for SharePoint Online
                string UserName = "userid@yoursite.onmicrosoft.com";
                //Replace it with your password
                string Password = "password";
                //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
                SecureString SecurePassword = GetSecureString(Password);
                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
                oClientContext.Load(oClientContext.Web.Lists.GetByTitle("TestList").Fields);
                oClientContext.ExecuteQuery();
                FieldCollection oFieldCollection = oClientContext.Web.Lists.GetByTitle("TestList").Fields;

                foreach(Field oField in oFieldCollection)
                {
                    Console.WriteLine(oField.Title);
                
                }
                Console.ReadLine();
            }
        }
    }
}

image

 Subscribe to my blog

Leave a Reply