I was recently presented with the task of allowing subfolders to be created automatically whenever a new folder is added to a document library. I had my own ideas on how to go about this, and did some searching on the net to confirm, and found there were a couple of different snippets suggesting how to do it. Trouble is, in my instance, I needed an event handler that would create additional subfolders to the folder that was being created, at the time of creation. So I fooled around with it a bit, an voila! Here's what I came up with:
SPSite site = web.Site;
SPListItem listItem = properties.ListItem;
SPList list = listItem.ParentList;
SPDocumentLibrary docLib = (SPDocumentLibrary)list;
if (properties.ListItem.ContentType.Name == "Folder" && properties.ListItem.Folder.ParentFolder.ToString() == docLib.RootFolder.ToString())
{
String url = listItem.ParentList.RootFolder.ServerRelativeUrl.ToString();
SPFolder curFolder = docLib.RootFolder.SubFolders[listItem.Name];
////Create subfolders:
SPFolderCollection folders = web.GetFolder(url).SubFolders;
string folderURL = (site.Url+"/"+curFolder.ToString());
SPListItem newFolder = docLib.Items.Add(folderURL, SPFileSystemObjectType.Folder, "Second Level 1");
SPListItem newFolder2 = docLib.Items.Add(folderURL, SPFileSystemObjectType.Folder, "Second Level 2");
newFolder.Update();
newFolder2.Update();
listItem.Update();
}
Granted, this may not be the most efficient code for the purpose intended, but it DOES work. Feel free to comment with anything you might suggest that I should change, and why you feel that way.
Hope this helps!
Rodney