In one of our SharePoint online projects, we are creating multiple lists and associating our custom specific content type to those. But somehow the lists are not getting created properly and most of those are corrupted. For some lists, content types are not associated. We were doing all these operations using JavaScript Object Model (JSOM). In this case, we had to delete all these lists and then create them again. Here, we have the option of either using PowerShell script or CSOM. In this scenario, I always prefer CSOM since it is easier to implement as compared to PowerShell.
Here, the code is pretty simple.
Steps for deleting the list using CSOM and console application,
- Create C# console application in Visual Studio. Here, I am using Visual Studio 2017 community edition.
- Add the reference to following two client DLLs,
- SharePoint.Client.dll
- SharePoint.Client.Runtime.dll
To add these references, we need to install SharePoint Online Client Components SDK .
- Connect to O365,
- We are storing our SharePoint online site URL, user name, and password in configuration file. Get the details to connect O365.
-
- string siteURL = ConfigurationSettings.AppSettings["siteURL"];
- string userName = ConfigurationSettings.AppSettings["userName"];
- string password = ConfigurationSettings.AppSettings["password"];
- Create the client context object and set the credentials.
- ClientContext clientContext = new ClientContext(siteURL);
- SecureString securePassword = new SecureString();
- foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
- clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
- Load the web object and get all lists.
-
- Web web = clientContext.Web;
- clientContext.Load(web);
-
-
- ListCollection allList = web.Lists;
- clientContext.Load(allList);
-
- clientContext.ExecuteQuery();
- The next step is to find the lists which we need to delete.
-
- ArrayList listArray = new ArrayList();
-
-
- string myContentTypeID = "0x01007931F4F9F69E0443972158D57498131A00A96BC22822FD7D40817DBAB3343D80AA";
-
- foreach(List _list in allList)
- {
-
- ContentTypeCollection ctCollection = _list.ContentTypes;
-
-
-
- ContentType ct = _list.ContentTypes.GetById(myContentTypeID);
- clientContext.Load(ct);
- clientContext.ExecuteQuery();
-
- bool? isCT = ct.ServerObjectIsNull;
-
-
- StringComparison.InvariantCultureIgnoreCase))
- {
- listArray.Add(_list.Title);
- }
- }
-
- for (int i = 0; i < listArray.Count; i++)
- {
- string listTitle = listArray[i].ToString();
- Console.WriteLine("List Deleting - :" + listTitle);
- allStudentList.GetByTitle(listArray[i].ToString()).DeleteObject();
- Console.WriteLine("List deleted successfully " + listTitle);
- web.Update();
- clientContext.ExecuteQuery();
- }
Thanks!
As usual, comments / suggestions / feedback / questions are always welcome!