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.


