Sometimes we have to query a SharePoint list through remote connections using C#. It can happen in a SharePoint App, a Console Application or maybe on an Azure Function. This post will help on performing list operations with CSOM and C# in SharePoint.

Below you can find some code snippets that will help you on integrating SharePoint lists with your application.

Basically, you will have to add the Microsoft.SharePoint.Client namespace.

using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

The required DLLs for programming these type of solution are:

Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll

You can find them inside those folders:

SharePoint 2010: 14 Hive -> Folder: ISAPI

SharePoint 2013: 15 Hive -> Folder: ISAPI

Or just download it from MSDN, inside the SharePoint Server 2013 Client Components SDK!

After adding these references to our project, we can start coding and accessing the data in the SharePoint List you want!

A custom list creation screen

Soon you will notice that everything depends on the ClientContext object, which manages the requests and the data that will be loaded.

In our examples we are going to use the variable siteUrl, that represents the URL for the Site Collection. The variable listTitle will also be used and it represents the Title of the list being used.

string siteUrl = "http://sitesharepoint";
string listTitle = "SharePointList";

So, let’s do some real stuff here:

Read operation in SharePoint lists

// creates a new SharePoint context
// passing the parameters
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("wiliammbr", "password", "domain");
// selects the list by title
SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);
// requests the item collection, without filters
SP.ListItemCollection itemCollection = list.GetItems(new CamlQuery());
// loads the item collection object in the context object
clientContext.Load(itemCollection);
// executes everything that was loaded before (the itemCollection)
clientContext.ExecuteQuery();
// iterates the list printing the title of each list item
foreach (SP.ListItem item in itemCollection)
{
Console.WriteLine(item["Title"]);
}

Filtering and selecting specific fields

The example below presents a simple code that queries only one list item from the List and specifies some specific columns to be returned. It’s important to say that exists lots of best practices to build good queries in SharePoint.

// creates a new SharePoint context
// passing the parameters
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("wiliammbr", "password", "domain");
// selects the list by title
SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);
// builds the caml query
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = string.Format(
@" <View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>{0}</Value>
</Eq>
</Where>
</Query>
<ViewFields>
<FieldRef Name='ID'/>
<FieldRef Name='Title'/>
<FieldRef Name='SomeDate'/>
<FieldRef Name='OtherField'/>
<FieldRef Name='Modified' />
</ViewFields>
<RowLimit>1</RowLimit>
</View>", "Some specific item");
// reads the item with the specified caml query
SP.ListItemCollection itemCollection = list.GetItems(camlQuery);
// tells the ClientContext object to load the collect,
// while we define the fields that should be returned like:
// Id, Title, SomeDate, OtherField and Modified
clientContext.Load(itemCollection,
items => items.Include(
item => item.Id,
item => item["Title"],
item => item["SomeDate"],
item => item["OtherField"],
item => item["Modified"]));
// executes everything that was loaded before (the itemCollection)
clientContext.ExecuteQuery();
// iterates the list printing the title and another field of each list item
foreach (SP.ListItem item in itemCollection)
{
Console.WriteLine(string.Concat(item["Title"], " - ", item["OtherField"]));
}

Creation operation in SharePoint lists

// creates a new SharePoint context
// passing the parameters
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("wiliammbr", "password", "domain");
// selects the list by title
SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);
// creates a new object to include the new list item
// this object helps you on defining which target folder the list item
// is going to be saved and other settings
SP.ListItemCreationInformation itemCreateInfo = new SP.ListItemCreationInformation();
// adds the new item to the list with ListItemCreationInformation
SP.ListItem listItem = list.AddItem(itemCreateInfo);
// fill the fields with the required information
listItem["Title"] = "New Item!";
listItem["OtherField"] = "Some important information.";
listItem.Update();
// executes the creation of the new list item on SharePoint
clientContext.ExecuteQuery();

 Update operation in SharePoint lists

// creates a new SharePoint context
// passing the parameters
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("wiliammbr", "password", "domain");
// selects the list by title
SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);
// gets an specific list item by its id
SP.ListItem listItem = list.GetItemById(1);
// changes some fields
listItem["Title"] = "Este item foi atualizado";
listItem.Update();
// executes the update of the list item on SharePoint
clientContext.ExecuteQuery();

 Delete operation in SharePoint lists

// creates a new SharePoint context
// passing the parameters
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("wiliammbr", "password", "domain");
// selects the list by title
SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);
// gets an specific list item by its id
SP.ListItem listItem = list.GetItemById(1);
// deletes the object. it's not necessary to update the item
listItem.DeleteObject();
// executes the exclusion of the list item on SharePoint
clientContext.ExecuteQuery();

I believe these are the basics for consuming SharePoint lists. In the future I’m planning to show some complex examples, more focused on Office 365 and Azure integrations. Thanks for reading and I hope it can be useful to you when you need to perform list operations with CSOM and C# in SharePoint.

References:
MSDN