0

I'm with SP13 On-prem and I want to delete all items from lists and all folder in doclibraries in recycle bin...

This is my code for list:

if (list.BaseType == SPBaseType.GenericList)
{
      while (list.Items.Count > 0)
      {
          list.Items[0].Recycle();
      }
}

Error message: Collection was modified; enumeration operation may not execute. Error stackTrace: at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System .Collections.IEnumerator.MoveNext()

And.....items not moving in recycle

This is code for doclib:

    if (list.BaseType == SPBaseType.DocumentLibrary)
    {
          string libURL = oWeb.Url + "/" + list.RootFolder.Url;
          SPFolderCollection folders = oWeb.Folders[libURL].SubFolders;
          foreach (SPFolder folder in folders)
          {
              if (!folder.Name.Contains("Forms"))
              {
                 oWeb.Folders[libURL].SubFolders.Delete(folder.Url).Recyclebin();
              }
          }
}

How to delete folder in Recycle ??

3

To send items to Recycle bin, you can do like this:

//Custom List
if (list.BaseType == SPBaseType.GenericList)
{
    SPListItemCollection coll = list.Items;

    foreach (SPListItem listitem in coll)
    {
        SPListItem itemToDelete = list.GetItemById(listitem.ID);
        itemToDelete.Recycle();
    }
}

// Document Library
if (list.BaseType == SPBaseType.DocumentLibrary)
{
    string libURL = oWeb.Url + "/" + list.RootFolder.Url;
    SPFolderCollection folders = oWeb.Folders[libURL].SubFolders;

    foreach (SPFolder folder in folders)
    {
        if (!folder.Name.Contains("Forms"))
        {
            SPListItem itemToDelete = list.GetItemById(folder.Item.ID);
            itemToDelete.Recycle();
        }
    }
}

UPDATE: Your code also fails on:

foreach (SPList list in fundListsAndLibs)

So I adapted your code, getting lists Title and then retrieving each list by Title, making no difference between lists and libraries and extracting firstly items and then only first level folders.

SPSecurity.RunWithElevatedPrivileges(delegate ()
{
    try
    {
        using (SPSite oSite = new SPSite(fundURL))
        {
            using (var oWeb = oSite.OpenWeb())
            {
                oWeb.AllowUnsafeUpdates = true;

                // Get lists Title
                var fundListsAndLibs = (from SPList list in oWeb.Lists select list.Title);

                // To Skip Titles
                var skipLibs = new[] { "DataAccessLib", "Pages" };

                // Extract desidered Lists Title
                var desideredLists = fundListsAndLibs.Where(l => !skipLibs.Contains(l)).ToList();


                foreach (string listName in desideredLists)
                {
                    // Try get list
                    var list = oWeb.Lists.TryGetList(listName);
                    if (list == null) continue;

                    // Retrieve only items
                    var queryItems = new SPQuery();
                    queryItems.ViewXml = "<View Scope='Recursive'></View>";
                    var items = list.GetItems(queryItems);
                    foreach (SPListItem listitem in items)
                    {
                        SPListItem itemToDelete = list.GetItemById(listitem.ID);
                        itemToDelete.Recycle();
                    }

                    // Retrieve only first level folders
                    var query = new SPQuery();
                    query.ViewXml = string.Format(@"<View Scope='RecursiveAll'>
                                                        <Query>
                                                            <Where>
                                                            <And>
                                                                <Eq>
                                                                    <FieldRef Name='FSObjType' />
                                                                    <Value Type='Integer'>1</Value>
                                                                </Eq>
                                                                <Eq>
                                                                    <FieldRef Name='FileDirRef'/>
                                                                    <Value Type='Text'>{0}</Value>
                                                                </Eq>
                                                            </And>
                                                            </Where>
                                                        </Query>
                                                    </View>"
                                                    , list.RootFolder.ServerRelativeUrl);
                    var folders = list.GetItems(query);
                    foreach (SPListItem listitem in folders)
                    {
                        SPListItem itemToDelete = list.GetItemById(listitem.ID);
                        itemToDelete.Recycle();
                    }
                }

                oWeb.AllowUnsafeUpdates = false;
            }

        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error message: " + ex.Message + " Error stackTrace: " + ex.StackTrace);
    }
});
  • With this code i have this error: Error message: Collection was modified; enumeration operation may not execute. E rror stackTrace: at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System .Collections.IEnumerator.MoveNext() – Goshky Jan 5 '17 at 11:50
  • And the items doesnt go to the Recycle bin... – Goshky Jan 5 '17 at 11:51
  • I tested the code and it's working. Can you please attach the entire code you are using? – Cecilia Jan 5 '17 at 12:20
  • Where i'm wrong? – Goshky Jan 5 '17 at 14:23
  • Take a look on the updated answer. I adapted your code. – Cecilia Jan 5 '17 at 14:36
2

For sharepoint list, use below code:

if (list.BaseType == SPBaseType.GenericList)
{
    if (list != null)
    {
        int itemCount = list.ItemCount;
        for (int k=0; k<itemCount; k++)
        {
            listItems[k].Recycle();

        }   
    }   
}

Or use the Batchcommand to delete all list items as below:

public static void DeleteAllItems(string site, string list)
{
    using (SPSite spSite = new SPSite(site))
    {
        using (SPWeb spWeb = spSite.OpenWeb())
        {
            StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);
            spSite.RootWeb.ProcessBatchData(deletebuilder.ToString());
        }
    }
}

private static StringBuilder BatchCommand(SPList spList)
{
    StringBuilder deletebuilder= new StringBuilder();
    deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
    string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
        "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"owsfileref\">{1}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

    foreach (SPListItem item in spList.Items)
    {
        deletebuilder.Append(string.Format(command, item.ID.ToString(),item["FileRef"].ToString()));
    }
    deletebuilder.Append("</Batch>");
    return deletebuilder;
}

reference - Deleting all the items

// We prepare a String.Format with a String.Format, this is why we have a {{0}} 
string command = String.Format("<Method><SetList Scope=\"Request\">{0}</SetList><SetVar Name=\"ID\">{{0}}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar><SetVar Name=\"owsfileref\">{{1}}</SetVar></Method>", list.ID);
// We get everything but we limit the result to 100 rows 
SPQuery q = new SPQuery();
q.RowLimit = 100;

// While there's something left 
    while (list.ItemCount > 0)
    {
        // We get the results 
        SPListItemCollection coll = list.GetItems(q);

        StringBuilder sbDelete = new StringBuilder();
        sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

        Guid[] ids = new Guid[coll.Count];
        for (int i=0;i<coll.Count;i++)
        {
         SPListItem item = coll[i];
         sbDelete.Append(string.Format(command, item.ID.ToString(), item.File.ServerRelativeUrl));
         ids[i] = item.UniqueId;
        }
        sbDelete.Append("</Batch>");

        // We execute it 
        web.ProcessBatchData(sbDelete.ToString());

        list.Update();
    }

Deleting all the items from a list

  • with first code error is: Collection was modified; enumeration operation may not execute. E rror stackTrace: at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System .Collections.IEnumerator.MoveNext() – Goshky Jan 5 '17 at 12:17
  • Item is deleted, but not go to Recycle bin... and throw above exception – Goshky Jan 5 '17 at 12:18
  • Check updated code. – Gautam Sheth Jan 5 '17 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.