SharePoint .NET Client Object Model Examples

As a SharePoint developer, you should understand the Client Side Object Model (CSOM). By using CSOM, you can interact with SharePoint sites and data from external applications without direct server access.

The SharePoint .NET Client Object Model works consistently across multiple versions, including SharePoint On-Premises and SharePoint Online.

What is SharePoint CSOM?

SharePoint Client Object Model (CSOM) offers APIs that let users work remotely with SharePoint data. Unlike server-side code, CSOM has some limitations:

  • Cannot access farm-level settings (only web application level)
  • Cannot use privilege elevation
  • No need for SharePoint installation on development machines

The big advantages of CSOM include:

  • Only requires client DLLs for development
  • No compilation needed
  • No IIS resets required

CSOM allows building applications that interact with SharePoint without direct server access.

Here is how SharePoint CSOM works:

SharePoint Client-Side Object Model (CSOM) operates through a bundling process. When you use CSOM APIs to perform tasks, the .NET client object model packages your commands into XML format. This package remains on the client side until you call the ExecuteQuery method. At that point, the bundled commands are sent to the server for processing. This approach helps optimize performance by sending multiple commands in a single server request.

SharePoint .NET Client Object Model Examples

Create a Console App for SharePoint CSOM Integration

To work with SharePoint using the Client Side Object Model (CSOM), start by setting up a console application in Visual Studio. This approach lets you interact with SharePoint sites programmatically without direct server access.

First, add the required libraries to your project through NuGet:

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

If you’ve installed SharePoint SDKs, you can also reference the DLLs from:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin

Choose the SDK that matches your environment:

After setting up your project, you can write simple code to connect to and query SharePoint. Here’s a basic example that retrieves SharePoint site information:

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

void GetSiteInfo()
{
    // SharePoint Online site URL
    string siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
    
    // Credentials for SharePoint Online
    string userName = "[email protected]";
    string password = "yourpassword";
    
    // Convert password to secure string
    SecureString securePassword = new SecureString();
    foreach (char c in password)
    {
        securePassword.AppendChar(c);
    }
    
    // Create SharePoint Online credentials
    SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(userName, securePassword);
    
    // Create ClientContext with the SharePoint Online site URL
    ClientContext context = new ClientContext(siteUrl);
    
    // Assign the credentials
    context.Credentials = credentials;
    
    // Get the site (Web) object
    Web site = context.Web;
    
    // Load the site properties
    context.Load(site);
    
    // Execute the query to retrieve the data
    context.ExecuteQuery();
    
    // Access site properties
    string siteTitle = site.Title;
    string siteDescription = site.Description;
    
    // Use the site information as needed
    Console.WriteLine($"Site Title: {siteTitle}");
    Console.WriteLine($"Site Description: {siteDescription}");
}

This code creates a connection to your SharePoint site, loads the web object, and retrieves its title and description properties.

Check out SPServices in SharePoint

SharePoint CSOM Examples

Now, let me show you some examples of SharePoint CSOM.

Get Current User Details using CSOM

Similarly, we can retrieve logged-in user details by using the Client-Side Object Model (CSOM). To run client-side code, we need the following two dlls:

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

Code:

using (ClientContext context = new ClientContext("http://Site URL"))
{
NetworkCredential myNetCred = new NetworkCredential("akashkumhar", "admin@123");
context.Credentials = myNetCred;
Web web = context.Web;
context.Load(web);
User user = context.Web.CurrentUser;
context.Load(user);
context.ExecuteQuery();
Console.Write("CSOM\nUser Information\nUser ID : " + user.Id + "\nUser Login Name : " + user.LoginName + "\nUser Title: " + user.Title);
Console.ReadLine();
}

Output:

sharepoint get current user

As shown in the above screenshot, it displays the current SharePoint user.

Get Selected Properties of SharePoint Site using CSOM

In CSOM, when you execute this code: context.Load(web); it will load all the properties of the SharePoint site.

However, suppose we only need two properties, such as Title and Description, then it is unnecessary to retrieve all properties from the server to the client. The client object model provides anonymous methods that utilize lambda expressions to request specific property names.

Below is the full code to retrieve the title of a SharePoint site using client object model code.

using Microsoft.SharePoint.Client;

ClientContext context = new ClientContext("http://URL of the Site");
Web web = context.Web;
context.Load(web, w => w.Title, w => w.Description);
context.ExecuteQuery();
string Title = web.Title;
string Description = = web. Description;

Create a SharePoint List Programmatically using CSOM

You can easily create a SharePoint list programmatically using CSOM. The below code will create an announcement list in SharePoint using csom.

Here I have used the Announcements list template, you can also use other list template ids.

using (ClientContext context = new ClientContext(“http://bsahoo3:8787/sites/Training”))
{
//Create a new list
ListCreationInformation listCreationInformation = new ListCreationInformation();
listCreationInformation.Title = "My Announcements List";
listCreationInformation.Description += "Here is my list created by client object midel";
listCreationInformation.TemplateType = (int)ListTemplateType.Announcements;
listCreationInformation.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
List list = context.Web.Lists.Add(listCreationInformation);
context.ExecuteQuery();
}

Once you execute the csom SharePoint code, it will create a list named “My Announcements List”.

Update SharePoint List Programmatically using CSOM

Now, we will see how we can update the list title and description using SharePoint .NET managed client object model (CSOM).

ClientContext context = new ClientContext(“http://WebSiteUrl”);
Web web = context.Web;
List myList = web.Lists.GetByTitle("My New List");
myList.Title = "My New List Modified";
myList.Description="This is modified list description!";
list.Update();
context.ExecuteQuery();

Once you execute the SharePoint client side object model code, the list title will be changed from My New List to My New List Modified.

Delete a SharePoint list programmatically using CSOM

Below is the SharePoint client object model code to delete a SharePoint list programmatically using CSOM.

ClientContext context = new ClientContext(“http://WebSiteUrl”);
Web web = context.Web;
List list = web.Lists.GetByTitle("My New List");
list.DeleteObject();
context.ExecuteQuery();

This csom sharepoint example helps to delete the SharePoint list programmatically from the SharePoint site.

You can also use the below SharePoint Online code:

public void DeleteTemporaryList(string URL)
{
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List tempList;
try
{
tempList = clientContext.Web.Lists.GetByTitle(“MyTempList”);
clientContext.Load(tempList);
clientContext.ExecuteQuery();
tempList.DeleteObject();
clientContext.ExecuteQuery();
}

catch (Exception ex)
{
}
}
}

private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

Check out Redirect SharePoint Site To New URL

Check if List Exists in SharePoint using CSOM

As a SharePoint developer, many times you might be required to check if a list exists in SharePoint using CSOM.

In CSOM SharePoint, no direct method will return whether the list is presented or not. If the list does not exist, then when we run the context.ExecuteQuery(); it will go to the exception block, and it will return a message like below:

List ‘MyListName’ does not exist at site with URL ‘https://tsinfotechnologies.sharepoint.com/sites/Marketing’.

So, from the exception, we have to catch that the list does not exist. The full code is as follows:

private void btnClick_Click(object sender, EventArgs e)
{
bool isListExists = IsListExist();
}

private bool IsListExist()
{
bool isExists = false;
using (ClientContext context = new ClientContext(“https://tsinfotechnologies.sharepoint.com/sites/Marketing/”))
{
string username = "********@tsinfotechnologies.onmicrosoft.com";
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in “********”)
{
secureString.AppendChar(c);
}
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
List lst = context.Web.Lists.GetByTitle("MyListName");
context.Load(lst);
context.ExecuteQuery();
if (lst != null)
{
if (lst.ItemCount >= 0)
{
isExists = true;
}
}
}

catch (Exception ex)
{
isExists = false;
}
}
return isExists;
}

This is how to check if a SharePoint list exists programmatically using C#.

Read Create and Manage Task List in SharePoint

Get SharePoint List Column Names using CSOM

Learn how to get column names of a SharePoint list using the SharePoint client object model.

ClientContext context = new ClientContext(“http://URL of the Site”);
Web web = context.Web;
List list = site.Lists.GetByTitle(“ListName”);
context.Load(list);
context.ExecuteQuery();
FieldCollection fieldCollection = list.Fields;
context.Load(fieldCollection);
context.ExecuteQuery();
foreach (Field field in fieldCollection)
{
Console.WriteLine(“Name: ” + field.InternalName.ToString());
}
Console.ReadLine();

The above csom code will display all columns from the SharePoint list.

Below is the SharePoint client object model code to get the SharePoint column display name and internal name using the SharePoint client object model.

string url = "http://SiteURL";
ClientContext context = new ClientContext(url);
Web web = context.Web;
var list = web.Lists.GetByTitle("Announcements");
context.Load(list.Fields);
context.ExecuteQuery();
string title = string.Empty;
string internalName = = string.Empty;
foreach (Field f in list.Fields)
{
title += field.Title + " ";
internalName += field.InternalName + " ";
}

Insert an item into a SharePoint List

We can easily insert the item into a SharePoint list using the .NET client object model in SharePoint.

Here I have a custom SharePoint list having 3 columns: Title, Description & TaskStatus.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);

ListItemCreationInformation newItem = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem listItem = list.AddItem(newItem);
listItem[“Title”] = “New Item Added”;
listItem[“Description”] = “New Item Description”;
listItem[“TaskStatus”] = “False”;
listItem.Update();
context.ExecuteQuery();

Check out Include jQuery in SharePoint

Update SharePoint list items using CSOM

Below is the CSOM code to update all items from a SharePoint list.

ClientContext context = new ClientContext("http://bsahoo3:2500/sites/MyTest/");
List list = context.Web.Lists.GetByTitle("MyCustomList");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);

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

foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
item["Title"] = item["Title"] + " Modified";
item.Update();
}
context.ExecuteQuery();

The above code will update each SharePoint list item and will add Modified with the existing title.

Delete SharePoint List item

Now, we will discuss how to delete a list item programmatically using the SharePoint client object model. The below CSOM SharePoint code will delete an item whose title is “New Task.”

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);

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

foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
if (item[“Title”].ToString() == "New Task")
item.DeleteObject();
break;
}

Here, we saw how to use the client object model in SharePoint.

Read JavaScript Examples [51 Useful Examples]

Get SharePoint list items and display in Gridview using CSOM

Now we will see how to get list items and display them in a gridview using the SharePoint .NET client object model.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
context.Load(list);
context.Load(items);
context.ExecuteQuery();
DataTable table = new DataTable();
table.Columns.Add(“Id”);
table.Columns.Add(“Title”);
foreach (Microsoft.SharePoint.Client.ListItem item in items)
table.Rows.Add(item.Id, item[“Title”]);
GridView1.DataSource = table;
GridView1.DataBind();

The above csom sharepoint code will read all list items and will show the list data in a gridview.

Check out Retrieve SharePoint List Items Using Power Automate

Create a SharePoint List, Add Columns, and Add Items using CSOM

I will show you the complete code to create a SharePoint list, add a column, and then add items to the SharePoint Online list using CSOM.

using System;
using Microsoft.SharePoint.Client;
class Program
{
static void Main()
{
ClientContext clientContext =new ClientContext(“http://intranet.contoso.com”);
Web site = clientContext.Web;
// Create a list.

ListCreationInformation listCreationInfo =new ListCreationInformation();
listCreationInfo.Title = “Client API Test List”;
listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
List list = site.Lists.Add(listCreationInfo);

// Add fields to the list.
Field field1 = list.Fields.AddFieldAsXml(
@”<Field Type=’Choice’
DisplayName=’Category’
Format=’Dropdown’>
<Default>Specification</Default>
<CHOICES>
<CHOICE>Specification</CHOICE>
<CHOICE>Development</CHOICE>
<CHOICE>Test</CHOICE>
<CHOICE>Documentation</CHOICE>
</CHOICES>
</Field>”,true, AddFieldOptions.DefaultValue);

Field field2 = list.Fields.AddFieldAsXml(
@”<Field Type=’Number’ DisplayName=’Estimate’/>”,true, AddFieldOptions.DefaultValue);

// Add some data.

ListItemCreationInformation itemCreateInfo =new ListItemCreationInformation();
ListItem listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Write specs for user interface.”;
listItem[“Category”] = “Specification”;
listItem[“Estimate”] = “20”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Develop proof-of-concept.”;
listItem[“Category”] = “Development”;
listItem[“Estimate”] = “42”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Write test plan for user interface.”;
listItem[“Category”] = “Test”;
listItem[“Estimate”] = “16”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Validate SharePoint interaction.”;
listItem[“Category”] = “Test”;
listItem[“Estimate”] = “18”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Develop user interface.”;
listItem[“Category”] = “Development”;
listItem[“Estimate”] = “18”;
listItem.Update();
clientContext.ExecuteQuery();
}
}

Check out SharePoint Rest API Tutorial and Examples

Add a User to a SharePoint group using CSOM

In this SharePoint client object model example, I will show you how to add a user to a SharePoint group using the SharePoint client object model.

ClientContext context = new ClientContext(“http://SiteURL”);
GroupCollection siteGroups = context.Web.SiteGroups;
// Here it will retrieve the group whose ID=1
Group myGroup = siteGroups.GetById(1);
UserCreationInformation userInfo = new UserCreationInformation();
userInfo.Email = “[email protected]”;
userInfo.LoginName = “enjoysharepoint\\User1”;
userInfo.Title = “Admin EnjoySharePoint”;
User newUser = membersGroup.Users.Add(userInfo);
context.ExecuteQuery();

Once you execute the CSOM SharePoint code, it will add the above user to the SharePoint group (myGroup) using CSOM.

Get All Users from SharePoint Group Programmatically using CSOM

In this SharePoint example, I will show you how to get all the users from a SharePoint group using CSOM.

Below is the CSOM code to get all users from the SharePoint group programmatically using csom.

ClientContext context = new ClientContext(“http://SiteURL”);
GroupCollection siteGroups = context.Web.SiteGroups;
// Here it will retrieve the group whose ID=1
Group myGroup = siteGroups.GetById(1);
context.Load(myGroup.Users);
context.ExecuteQuery();
foreach (User member in myGroup.Users)
{
lblUsers.Text = lblUsers.Text + “, ” + member.Title;
}

You can also use the below CSOM code:

public static string GetPortalOwnerEmail(string URL)
{
string ownerEmail = string.Empty;
using (ClientContext context = new ClientContext(URL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(“My Custom SharePoint Group”);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
ownerEmail += usr.Email+”,”;
}

}
return ownerEmail;
}

private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}

Check out Reset Id In SharePoint List

Get SharePoint Site Level Content Types using CSOM

Below is the CSOM code to get all SharePoint site-level content types.

using Microsoft.SharePoint.Client;

ClientContext context = new ClientContext("http://URL of the Site");
Web web = context.Web;
context.Load(site);
context.ExecuteQuery();
ContentTypeCollection contentTypeCollection = site.ContentTypes;
context.Load(contentTypeCollection);
context.ExecuteQuery();
foreach (ContentType contentType in contentTypeCollection)
{
Console.WriteLine(contentType.Name);
}
Console.ReadLine();

Get ModerationStatus of a Document using CSOM

I will show you here how to retrieve the ModerationStatus of a document using csom (.NET managed object model) code in SharePoint Online.

Here I have a SharePoint document library and I want to retrieve the ModerationStatus for a particular document. I am filtering record whose ID is 10.

Moderation Status is a 4-byte integer indicating the moderation approval status of a list item. Configurations can require moderation approval to publish a list item or allow automatic approval. A published list item MUST have a Moderation Status of 0. The following are all possible valid values for Moderation Status.

ValueDescription
0The list item is approved.
1The list item has been denied approval.
2The list item is pending approval.
3The list item is in the draft or checked out state.
4The list item is scheduled for automatic approval at a future date.

Below is the full code to retrieve the ModerationStatus of a document using csom (.NET managed object model) code in SharePoint Online

public string GetItemApprovalStatus(string URL)
{
string status = string.Empty;
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
List oList = clientContext.Web.Lists.GetByTitle("MyTestList");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name=’ID’/><Value Type = 'Int' > 10 </Value ></Eq></Where></Query></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
string NodeStatus = oListItem["_ModerationStatus"].ToString();
if (NodeStatus == "0")
{
status = "Approved";
}
else if (NodeStatus == "1")
{
status = "Denied";
}
else if (NodeStatus == "2")
{
status = "Pending";
}
else if (NodeStatus == "3")
{
status = "Draft";
}
else if (NodeStatus == "4")
{
status = "Scheduled";
}
}
}
return status;
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

This code will return the ModerationStatus of a document using csom in SharePoint Online.

Add Lookup Column to SharePoint List Programmatically using CSOM

I will show you here how to add lookup column programmatically using csom in SharePoint.

There are two SharePoint lists, where, from one we need to get Title as a lookup field display name and in the second list we need to show the title field as a column value.

Here we have a SharePoint list named ” SourceListName ” with a column as Title. The list looks like this:

Add lookup column to SharePoint list programmatically

And I have another list known as DestinationList which has a Title column. And here we need to add a lookup column to this list.

Below is the full code to add a lookup column to the SharePoint list programmatically using CSOM (C#).

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace SPOnlineConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
using (ClientContext clientContext = new ClientContext("https://tsinfotechnologies.sharepoint.com/sites/Marketing/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List SourceListName = clientContext.Web.Lists.GetByTitle("SourceListName");
List DestinationList = clientContext.Web.Lists.GetByTitle("DestinationList");
clientContext.Load(SourceListName);
clientContext.Load(DestinationList);
clientContext.ExecuteQuery();
Field LookUpField = DestinationList.Fields.AddFieldAsXml(
"<Field Type='Lookup' DisplayName='Employees' Required='FALSE' List='" + SourceListName.Id + "' ShowField = 'Title' StaticName = 'Title' Name = 'Title' /> ", true, AddFieldOptions.DefaultValue);
LookUpField.Update();
clientContext.ExecuteQuery();
}
}

private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
}
}

Once we run the code, the lookup column will be added to the SharePoint list like below:

Add lookup column to SharePoint list programmatically using csom

Next time, when you add an item to the list, you can see the lookup data like below:

How to Add lookup column to SharePoint list programmatically

This is how to add a lookup column to the SharePoint list programmatically using client-side object model (csom).

Upload a File to the SharePoint Document Library using CSOM

Let us see how to upload a document to the SharePoint document library using CSOM (client-side object model) from the physical location.

Many times, a document must be uploaded from a physical path to the document library using the Client Side Object Model (csom) in SharePoint.

upload document to SharePoint document library programmatically

Below is the CSOM code to upload a document to the SharePoint document library programmatically using CSOM.

You can write the code inside a console application or a Windows Application in C#.NET.

static void Main(string[] args)
{

try
{
// Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
using(ClientContext client = newClientContext("http://servername146/sites/test/"))
{
//client.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Assume that the web site has a library named "FormLibrary".
var formLib = client.Web.Lists.GetByTitle("Documents");
client.Load(formLib.RootFolder);
client.ExecuteQuery();

// FormTemplate path, The path should be on the local machine/server !
string fileName = @ "C:\File.txt";

var fileUrl = "";

//Craete FormTemplate and save in the library.
using(var fs = newFileStream(fileName, FileMode.Open))
{
var fi = newFileInfo("test.txt"); //file Title
fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}

// Get library columns collection.
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();

Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);

ListItem item = newFile.ListItemAllFields;

item["Title"] = "test";
item.Update();
client.ExecuteQuery();
}

} catch (Exception ex)
{

}

}

Final Output:

csom upload file to document library in SharePoint

This is how we can use CSOM to upload a file to a document library in SharePoint.

Read CSV File from SharePoint Document Library Programmatically using CSOM

Let us see how to read a CSV file from a document library using the .NET client object model (csom) in SharePoint Online.

Here we have a csv file which has three columns:

  • SiteName
  • SiteURL
  • SiteDescription

And it has three rows of data, and the CSV file looks like this:

sharepoint read csv file programmatically

And we have uploaded the CSV file to a SharePoint document library (MyDocLib) like below:

read file from sharepoint document library using c#

Below is the full code to read the CSV file from the SharePoint document library using csom.

private void btnSubmit_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext("hthttps://tsinfotechnologies.sharepoint.com/sites/Marketing/"))
{
string username = "********@tsinfotechnologies.onmicrosoft.com";
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in ""********")
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
DataTable dt= ImportSiteList(context);
}
catch (Exception ex)
{
throw;
}
}
}

private DataTable ImportSiteList(ClientContext context)
{
try
{
List list = context.Web.Lists.GetByTitle("MyDocLib");
context.Load(list);
context.ExecuteQuery();
Folder folder = list.RootFolder;
FileCollection files = folder.Files;
context.Load(files);
context.ExecuteQuery();
DataTable dt = new DataTable("tblSiteLists");
foreach (Microsoft.SharePoint.Client.File f in files)
{
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, (string)f.ServerRelativeUrl);
if((string)f.ServerRelativeUrl == "/sites/Marketing/MyDocLib/Sites.csv")
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
string dataformat = line.Replace("\r\n", ",");
string[] strArray = dataformat.Split(‘,’);
dt.Columns.Add("SiteName", typeof(string));
dt.Columns.Add("SiteURL", typeof(string));
dt.Columns.Add("SiteDescription", typeof(string));
int j = 0;
DataRow dr = dt.NewRow();
for (int i = 3; i < strArray.Length – 1; i++)
{
dr[j] = strArray[i];
j++;
if (j == 3)
{
j = 0;
dt.Rows.Add(dr);
dr = dt.NewRow();
}
}
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}

The above code will return a data table that looks like the screenshot below:

sharepoint read csv file programmatically csom

This is how to read a CSV file from the SharePoint document library programmatically using CSOM.

Check out SharePoint 2010 to SharePoint 2013/2016/2019 Migration Steps

Get Content Type ID from Content Type Name using CSOM

First, we will see how to retrieve the content type name from the content type ID using .NET managed object model code (csom) in SharePoint Online.

Here in the below csom code, we are passing the content type name as “Document Set” and it will return the content type id of “Document Set” from the SharePoint Online site.

I have added a button in my Windows application called the method below.

private static string GetContentTypeIDFromName()
{
string contentTypeId = string.Empty;
using (ClientContext clientContext = new ClientContext("https://<tenantname>.sharepoint.com/sites/Marketing/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
Web web = clientContext.Web;
ContentTypeCollection contentTypeColl = web.ContentTypes;
clientContext.Load(contentTypeColl);
clientContext.ExecuteQuery();
foreach (ContentType ct in contentTypeColl)
{
if (ct.Name.Equals("Document Set"))
{
contentTypeId = ct.Id.ToString();
break;
}
}
}
return contentTypeId;
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

If you run the code, you can see it will return the content type ID like below:

Retrieve content type Id from content type name using CSOM

This way, we can retrieve the content type ID from the content type name csom in SharePoint Online.

Retrieve Content Type Name by ID using CSOM in SharePoint

In this example, I will show you how to retrieve the content type name by content type id using csom (.NET client object model C#) code in SharePoint.

Here in this example I have used the “Workflow Task (SharePoint 2013)” whose Id is “0x0108003365C4474CAE8C42BCE396314E88E51F”.

Once I run the code below, it will give me the content type name

Below is the full csom code to retrieve the content type name from the content type ID in SharePoint using csom.

public static void GetContentTypeByID()
{
string contentTypeName = string.Empty;
using (ClientContext context = new ClientContext("https://<tenant name>.sharepoint.com/sites/Marketing/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
ContentType ct = context.Web.ContentTypes.GetById("0x0108003365C4474CAE8C42BCE396314E88E51F");
context.Load(ct);
context.ExecuteQuery();
contentTypeName = ct.Name;
}
}
private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

Once you run the above code, you can see the result like below:

Retrieve Content type Name by Id using csom in SharePoint

Get List Content Types using CSOM in SharePoint

I will show you how to retrieve content types associated with a list using csom in SharePoint.

First, we can retrieve the SharePoint list using the GetByTitle method, and then we can retrieve all the content types by using the code below:

ContentTypeCollection contentTypeColl = lst.ContentTypes;

Below is the full csom code to retrieve all list content types in SharePoint.

public static void RetrieveListContentType()
{
string contentTypes = string.Empty;
using (ClientContext context = new ClientContext("https://<tenantname>.sharepoint.com/sites/Finance/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List lst = context.Web.Lists.GetByTitle("MyTestList");
ContentTypeCollection contentTypeColl = lst.ContentTypes;
context.Load(contentTypeColl);
context.ExecuteQuery();
foreach (ContentType ct in contentTypeColl)
{
contentTypes += ct.Name;
}
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

Once you run the above code, it will retrieve all content types associated with the MyTestList list in SharePoint.

Delete Content Type from SharePoint Online List using CSOM

In this CSOM example, we will discuss deleting a content type attached to a list using csom in SharePoint Online.

Here, I have a list named “MyTestList,” which is a SharePoint custom list. In that list, I have added the default Announcement content type.

Using the csom code, I am trying to retrieve the content type by its ID and then delete the object.

Below is the full code to delete a content type from the SharePoint list using csom.

public static void DeleteContentType()
{
using (ClientContext contextURL = new ClientContext("https://<tenantname>.sharepoint.com/sites/Marketing/"))
{
contextURL.AuthenticationMode = ClientAuthenticationMode.Default;
contextURL.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List lst = contextURL.Web.Lists.GetByTitle("MyTestList");
ContentType ct = lst.ContentTypes.GetById("0x010400BE88F9D0169DC14194092368A99093F1");
ct.DeleteObject();
contextURL.ExecuteQuery();
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

The above code will delete the content type from the SharePoint Online list.

Get All Content Types using CSOM in SharePoint

Below is the CSOM code to get all content types from a SharePoint site.

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security;
using Microsoft.SharePoint.Client;
using System.Data;

public partial class getDataFromSharePointOnline : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (ClientContext clientcontext = new ClientContext("https://tsinfotechnologies.sharepoint.com/sites/Marketing/"))
        {
            string pwd = "xyz";
            SecureString passWord = new SecureString();

            foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);

            clientcontext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
            ContentTypeCollection displayContentTypes = clientcontext.Web.ContentTypes;
            clientcontext.Load(displayContentTypes);
            clientcontext.ExecuteQuery();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));

            foreach (ContentType ContentTypes in displayContentTypes)
            {
                dt.Rows.Add(ContentTypes.Name, ContentTypes.Description);
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

I have added a GridView on this page to show all content type names with descriptions.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4">
                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                <RowStyle BackColor="White" ForeColor="#330099" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                <SortedAscendingCellStyle BackColor="#FEFCEB" />
                <SortedAscendingHeaderStyle BackColor="#AF0101" />
                <SortedDescendingCellStyle BackColor="#F6F0C0" />
                <SortedDescendingHeaderStyle BackColor="#7E0000" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Here is the O/P of this code.

sharepoint csom get all content types

Check if User Belongs to SharePoint Group using CSOM

I will show you how to check if a particular user belongs to a SharePoint group using .NET managed object model code (csom). Here, we will pass the user’s email ID, and the function will return whether the user is present in the group.

public static bool IsUserBelongsToSharePointGroup(string siteURL, string groupName, string email)
{
bool isUserExistInGroup = false;

using (ClientContext context = new ClientContext(siteURL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title, w => w.Url);
context.ExecuteQuery();

Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(groupName);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
if (email == usr.Email)
{
isUserExistInGroup = true;
break;
}
}

}
return isUserExistInGroup;
}

We can call the function like below:

bool isUserBelongsToGroup = IsUserBelongsToSharePointGroup(“https://tsinfotechnologies.sharepoint.com/sites/Finance/”, “Finance Owners”, “[email protected]”);

Once you run the code, it will return whether the user belongs to a group or not. It will give results like the following:

Check if user belongs to SharePoint group using CSOM

This is how to check if the user belongs to a SharePoint group using CSOM.

Conclusion

CSOM allows developers to interact with SharePoint data from outside the SharePoint environment using various programming languages. I have explained how to work with CSOM in SharePoint in this tutorial with a few useful and practical examples.

You may also like:

  • >

    Build a High-Performance Project Management Site in SharePoint Online

    User registration Power Apps canvas app

    DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

    Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App

    Power Platform Tutorial FREE PDF Download

    FREE Power Platform Tutorial PDF

    Download 135 Pages FREE PDF on Microsoft Power Platform Tutorial. Learn Now…