MOSS MVP

I've moved my blog to http://blog.falchionconsulting.com!. Please update your links. This blog is no longer in use--you can find all posts and comments at my new blog; I will no longer be posting to this site and comments have been disabled.

Thursday, July 10, 2008

Creating List/Library Folders Programmatically

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.

14 comments:

solutionizing.net said...

Refactored to use ParentWeb, this would be a great Extension Method.

Gary Lapointe said...

I'll have to look into that - that's a great idea.

Dinooz said...

I wonder if this code can help me to create a Folder Sctructure from a Main Document Library also ???

Gary Lapointe 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.

Plissskin said...

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.

Gary Lapointe said...

This is a little dated but it will tell you all about extension methods: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx.

You can easily change the method so it's not an extension method (just remove "this" from the parameter list).

Plissskin said...

Great info all around Gary, thank you very much...

Styr said...

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

Gary Lapointe said...

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.

Romesh said...

After creating a folder how do I set “created by” and “modified by” properties?

Gary Lapointe said...

You can't change those fields.

dijana said...

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

Gary Lapointe said...

It's been a while since I looked at this but I thought there was a property on the content type that exposed the folder?

BWL said...

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