Creating List/Library Folders Programmatically

Posted on Posted in Article, SharePoint 2007

I’ve got this method that I keep copying and pasting into different solutions so I figured I’d post it here in case someone else could benefit from it.  You would think that it would be really easy to create folders in a list or library but oddly enough (or, if you’ve done SharePoint development long enough you would say typically enough), it’s not.  So, here’s a simple little method to help you get a folder and have it created if it doesn’t already exist:

public static SPFolder GetFolder(this SPList targetList, string folderUrl)
{
    if (string.IsNullOrEmpty(folderUrl))
        return targetList.RootFolder;
 
    SPFolder folder = targetList.ParentWeb.GetFolder(targetList.RootFolder.Url + "/" + folderUrl);
 
    if (!folder.Exists)
    {
        if (!targetList.EnableFolderCreation)
        {
            targetList.EnableFolderCreation = true;
            targetList.Update();
        }
 
        // We couldn't find the folder so create it
        string[] folders = folderUrl.Trim('/').Split('/');
 
        string folderPath = string.Empty;
        for (int i = 0; i < folders.Length; i++)
        {
            folderPath += "/" + folders[i];
            folder = targetList.ParentWeb.GetFolder(targetList.RootFolder.Url + folderPath);
            if (!folder.Exists)
            {
                SPListItem newFolder = targetList.Items.Add("", SPFileSystemObjectType.Folder, folderPath.Trim('/'));
                newFolder.Update();
                folder = newFolder.Folder;
            }
        }
    }
    // Still no folder so error out
    if (folder == null)
        throw new SPException(string.Format("The folder '{0}' could not be found.", folderUrl));
    return folder;
}

The code is actually not that bad.  It takes in a web and a list (although I could have/should have modified it to just take in the list and get the web via the ParentWeb property, but I digress) and a folder.  After checking to see if it already exists it then splits the folder path on "/" and then loops through each creating the folders as it goes (if it doesn’t already exist).  So you’d call the method like this:

SPFolder folder = list.GetFolder("/subfolder1/subfolder1a");

Enjoy!

Update 7/11/2008: Per the suggestion in the comments I changed the code so that the method is an extension method instead.

16 thoughts on “Creating List/Library Folders Programmatically

  1. If you mean given a file system folder structure can this code replicate that structure in a sharepoint library then essentially, yes – you’d just have to loop through all your folders on the file system and append the relative path to the url for the list. Would be pretty easy.

    1. Very nice work!

      I was wondering if you could be so kind as to show me how you would create a folder structure from file system folder. I know you have said:

      “If you mean given a file system folder structure can this code replicate that structure in a sharepoint library then essentially, yes – you’d just have to loop through all your folders on the file system and append the relative path to the url for the list. Would be pretty easy.”

      But i just can’t figure out how to do it. Please help me.

  2. I am trying to create a web part that will archive document libraries. This method has great potential for me, but when I paste it into my webpart class I get a compiler error: “Extension methods must be defined in a non-generic static class”. I’m a bit new at all this, what is an extension method, and how do I “plug” them into my code? Any help appreciated.

  3. Hi! And thank you for great post. I’m using this method as a part of my event, and everything seems to go well until I try to browse in the newly created folder. I get a COMException 0x80004005. Any Ideas what I’m doing wrong?

    Stack Trace:

    [COMException (0x80004005): Cannot complete this action.

    Please try again.]

    Microsoft.SharePoint.Library.SPRequestInternalClass.GetFolderContentTypeOrder(String bstrWebUrl, String bstrFolderUrl, String& pbstrContentTypeOrder) +0

  4. Based on the stack trace it would appear that it can’t find the content type associated with the folder. Have you deleted the folder content type or something? Try adding/setting a content type to the folder after you create it.

  5. This is great and it works perfect, but i keep wondering how to add subfolder in an exiesting content type folder. I cant figure it out, how to find my content type folder??

    I am doing an webpart and not feature with SPItemEventReceiver.

    can you please help me!

    Thanks,

    dijana

  6. yeah, there is a property but only in SPItemEventReceiver Feature (as I know :)).
    thats why i can’t get my content type folder…

  7. I have requirement like…….I need a sub folder in a folder……..
    As I tried the following code snippet, but not working, Pls help me…

    $NewSubfolder = $libraryName.AddItem($Newfolder.ServerRelativeUrl, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $SubFolder.SName)

Comments are closed.