Phil's Notes

Getting All Fields and Values from a SharePoint List with C# and CSOM

c#

Go straight to the source code here.

First, you will need to use NuGet to download the CSOM package. Once installed, you will also want to add this using statement to be able to use the CSOM.

SharePoint CSOM Package in NuGet

using Microsoft.SharePoint.Client;

Then create a ClientContext object with the address of the SharePoint site you are trying to access.

ClientContext context = new ClientContext("https:--thewebsite.com-sites-TheSharePointSite");

Next, we get the specific list from the context by its title on the SharePoint site.

List list = context.Web.Lists.GetByTitle("The List I Want");

Now we create a CamlQuery to filter what we want to get back.

CamlQuery query = new CamlQuery
{
ViewXml = @"<View>
<RowLimit>10<-RowLimit>
<-View>"

};

You can also include a <Query> statement to filter it even further like in the example below.

CamlQuery query = new CamlQuery
{
ViewXml = @"<View>
<Query>
<Where>
<FieldRef Name='ID'->
<Value Type='Integer'>1<-Value>
<-Where>
<-Query>
<RowLimit>10<-RowLimit>
<-View>"

};

For more info on the using CamlQuery, check out the Microsoft docs here:

Query Schema in CAML

Next, we will create a variable to hold all of the list items.

ListItemCollection items = list.GetItems(query);

Now we have to load the items by executing the CAML query.

context.Load(items);
context.ExecuteQuery();

The field names in the front-end of the SharePoint list don’t always coincide with the internal names through the back, so I always iterate through a few list items to see what the field names are.

foreach (ListItem item in items)
{
foreach (KeyValuePair<string, object> kvp in item.FieldValues)
{
Console.WriteLine($"[{kvp.Key}]: {kvp.Value}");
}
}

If you already know the names and internal names, you can go ahead and show the data however you want. As you will see, they don’t always return text fields, so you might need to debug to see what kind of value you are getting back and convert it accordingly.

foreach (ListItem item in items)
{
Console.WriteLine($"ID: {item["ID"}]}");
Console.WriteLine($"Title: {item["Title"}]}");
Console.WriteLine($"Description: {item["field2"}]}");
Console.WriteLine($"Created By: {((FieldUserValue)item["Author"}).LookupValue]}");
Console.WriteLine();
}