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:
1public static SPFolder GetFolder(this SPList targetList, string folderUrl)
2{
3 if (string.IsNullOrEmpty(folderUrl))
4 return targetList.RootFolder;
5
6 SPFolder folder = targetList.ParentWeb.GetFolder(targetList.RootFolder.Url + "/" + folderUrl);
7
8 if (!folder.Exists)
9 {
10 if (!targetList.EnableFolderCreation)
11 {
12 targetList.EnableFolderCreation = true;
13 targetList.Update();
14 }
15
16 // We couldn't find the folder so create it
17 string[] folders = folderUrl.Trim('/').Split('/');
18
19 string folderPath = string.Empty;
20 for (int i = 0; i < folders.Length; i++)
21 {
22 folderPath += "/" + folders[i];
23 folder = targetList.ParentWeb.GetFolder(targetList.RootFolder.Url + folderPath);
24 if (!folder.Exists)
25 {
26 SPListItem newFolder = targetList.Items.Add("", SPFileSystemObjectType.Folder, folderPath.Trim('/'));
27 newFolder.Update();
28 folder = newFolder.Folder;
29 }
30 }
31 }
32 // Still no folder so error out
33 if (folder == null)
34 throw new SPException(string.Format("The folder '{0}' could not be found.", folderUrl));
35 return folder;
36}
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:
1SPFolder 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.