Delete SharePoint List Programmatically using C# (CSOM)

This SharePoint tutorial explains, how to delete SharePoint list programmatically c# (CSOM). In SharePoint Online, we can use only client-side technologies like csom, jsom or Rest API, etc. Here we got one requirement to delete a SharePoint 2013 Online list using csom programmatically.

Delete SharePoint list programmatically C#

We wanted to use csom c#.net managed object model in SharePoint online. We have created a console application to delete list using csom. Even if you are working on SharePoint provider-hosted add-in, you can also use the same code for SharePoint 2013 or SharePoint Online.

To work with CSOM (C#.Net managed object model), we have to use the below two dlls which can be downloaded from Nuget also.

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

Since we are trying to connect to a SharePoint online site, we are keeping the credentials in App.config file and retrieving by using below two methods:

  • GetSPOAccountName()
  • GetSPOSecureStringPassword()

Here we are retrieving the SharePoint list using the GetByTitle method. And we are deleting the list by calling the DeleteObject() method.

Below is the C#.net method to delete sharepoint list programmatically using c#.

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;
}
}

You may like following SharePoint JSOM tutorials:

I hope this will be helpful to know how to delete list programmatically using CSOM C#.Net managed object model code in SharePoint Online or SharePoint 2013/2016.

>