How to check if list exists in SharePoint online using .Net managed object model CSOM?


In this post we will discuss how we can check if list exists in SharePoint online using .Net managed object model code (CSOM). Here we will use a windows application where we will communicate with our SharePoint online (Download PDF for FREE) site.


To work with SharePoint objects we need to add the below details:

– Microsoft.SharePoint.Client
– Microsoft.SharePoint.Client.Runtime

In .Net client object model there is not direct method which will return whether the list is presented or not. If the list does not exits then when we run the context.ExecuteQuery(); it will go to the exception block and it will return message like below:



List ‘Employees1222222’ does not exist at site with URL ‘https://onlysharepoint2013.sharepoint.com/sites/Bhawana’.

So from the exception we have to catch that the list is not exists. Full code is like below:

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

private bool IsListExist()
{
bool isExists = false;
using (ClientContext context = new ClientContext(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”))
{
string username = “********@onlysharepoint2013.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(“Employees1222222”);
context.Load(lst);
context.ExecuteQuery();
if (lst != null)
{
if (lst.ItemCount >= 0)
{
isExists = true;
}
}
}

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

Read some sharepoint online tutorials:



Hope this will be helpful.

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Bhawana Rathore

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 8+ years of SharePoint experience as well as in .Net technologies . I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools . Now exploring more in SharePoint 2016 :) Hope here I can contribute and share my knowledge to the fullest. As I believe "There is no wealth like knowledge, and no poverty like ignorance"

View all posts by Bhawana Rathore →