As you all know, in 2007 SharePoint introduced a new feature to lists - creating items in sub folders. But apparently the API was not modified in an easy way to support working with this feature...
In my last project I had to create sub-folders in lists and list items in these folders from code, and found that it is not so simple.
We are doing a rating solution for SharePoint items (coming soon on our web site, for more information contact firstname.lastname@example.org), and wanted to create a new "item rating" list to store all ratings for all items on the same site.
For performence issues we wanted to create a sub folder for each list in the site and a second level folder for each item and create all ratings and comments in that folder.
The outcome of that project was 3 utilities methods that manages all that I need for working with folders and I thought it would be nice to publish them here - mainly because when I googled for it I didn’t find any good posts for that.
Here is how to use the utilities methods in your project:
SPList list = GetOrCreateList(web);//create your own...
//Create subfolder named "first level"
SPListItem folder = GetOrCreateFolderInList(list, list.RootFolder, "first level");
//Create subfolder named "second level"
folder = GetOrCreateFolderInList(list, folder.Folder, "second level");
//Create item in "second level" folder
SPListItem item = AddListItemInFolder(folder);
//Update meta data of new item
item["Rating"] = 5;
item["Comments"] = "";
item["ListID"] = list.ID.ToString("N");
item["ItemID"] = "ITEM_ID";
item["UserName"] = "shai...";
Here is the code for the utilities:
private SPListItem AddListItemInFolder(SPListItem parentFolder)
return parentFolder.ListItems.Add(parentFolder.Folder.ServerRelativeUrl, SPFileSystemObjectType.File);
private SPListItem GetOrCreateFolderInList(SPList parentList, SPFolder parentFolder, string folderName)
folderName = folderName.ToLower();
string parentFolderUrl = parentFolder == null ? "":parentFolder.ServerRelativeUrl.ToLower();
//Look in existing folders
foreach (SPListItem f in parentList.Folders)
if (f.Folder.ServerRelativeUrl.ToLower() == parentFolderUrl + "/" + folderName)
return f;//Found! return it!
//not exists - create
SPListItem folder = parentList.Items.Add(parentFolderUrl, SPFileSystemObjectType.Folder, folderName);
Well, hope this helps you - it sure did help me :)