Delete all SubFolders in a Document Library or Photo List

I ran across a task to delete all the subfolders in a Photo list today programmatically. Below is the code I came up to accomplish this. There is a more efficient way to accomplish this task using {spweb}.ProcessBatchData that I will write an article on later.

System.String listName = "Photos";

using (SPSite site = new SPSite("http://MySharePointSite/"))
    using (SPWeb web = site.OpenWeb("/"))
    {
        SPFolderCollection folders = web.Folders[listName].SubFolders;

        foreach (SPFolder folder in folders)
        {
            if (folder.Name != "Forms")
                web.Folders[listName].SubFolders.Delete(folder.Url);
        }
    }

Advertisements

One response to “Delete all SubFolders in a Document Library or Photo List

  1. Collection was modified; enumeration operation may not execute.:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s