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 ??

Goshky
  • 2,058
  • 4
  • 24
  • 48

2 Answers2

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);
    }
});
Cecilia
  • 984
  • 4
  • 12
  • 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 05 '17 at 11:50
  • And the items doesnt go to the Recycle bin... – Goshky Jan 05 '17 at 11:51
  • I tested the code and it's working. Can you please attach the entire code you are using? – Cecilia Jan 05 '17 at 12:20
  • Where i'm wrong? – Goshky Jan 05 '17 at 14:23
  • Take a look on the updated answer. I adapted your code. – Cecilia Jan 05 '17 at 14:36
  • Everything is good, no exception, but items doesnt go to the Recycle bin – Goshky Jan 05 '17 at 15:02
  • Items are still in lists/document libraries or not? Consider that running code with Elevated Privileges sends items to the Site Collection Recycle bin (_layouts/15/AdminRecycleBin.aspx) and not to the webs Recycle bin (_layouts/15/RecycleBin.aspx) – Cecilia Jan 05 '17 at 15:07
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

Gautam Sheth
  • 30,881
  • 1
  • 35
  • 62