Thursday, 10 October 2019

CSOM: How to delete all items in a SharePoint list?

using F = System.Windows.Forms;
using Microsoft.SharePoint.Client;
using PnP = OfficeDevPnP.Core;

try
            {
                PnP.AuthenticationManager authManager = new PnP.AuthenticationManager();
                using (ClientContext clientContext = authManager.GetWebLoginClientContext(txtSourceUrl.Text))
                {
                    List list = clientContext.Web.Lists.GetByTitle(drpLists.SelectedItem.ToString());
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = "<View><Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where></Query></View>";
                    ListItemCollection allItems = list.GetItems(camlQuery);
                    clientContext.Load(allItems);
                    clientContext.ExecuteQuery();
                    int itemCount = allItems.Count;
                    F.MessageBox.Show("Deletion is started. Please monitor the count on SharePoint.");
                    if (itemCount > 0)
                    {
                        for (int i = itemCount - 1; i > -1; i--)
                        {
                            allItems[i].DeleteObject();
                            clientContext.ExecuteQuery();
                        }
                    }
                    F.MessageBox.Show("Items are deleted.");
                }
            }
            catch (Exception ex)
            {
                F.MessageBox.Show("Error: " + ex.Message);
            }
        }

No comments:

Post a Comment