Creating a Content Type based Folder in SharePoint via Feature Receiver

Posted Monday, January 14, 2008 3:40 PM by C-Dog's .NET Tip of the Day

I have been working a lot with document libraries again and in this particular implementation, I had a need to create a pre-determined set of folders upon document library creation that were based upon a custom content type. I couldn't find a way to do it with CAML (maybe I am just a noob), so I decided to take the programatic approach. I ran into a couple of issues along the way so I thought I would point them out. When I first started out, I attempted to just treat the document library like a list, however when you go to create the item that way, you will get an error telling you to use SPFileCollection. In this case, I was creating a folder, so that didn't really make sense. So I started by going with a folder collection.

For this example, assume we are just working out of the FeatureActivated EHM. We need to get a reference to the current site and then to the list. Once we have the list, we can get a SPFolderCollection. Make sure to get the folder collection off of RootFolder, because things will not work if you don't.

   27 SPWeb currentSite = (SPWeb)properties.Feature.Parent;

   28             SPFolderCollection documentLibrary = currentSite.Lists["My Document Library"].RootFolder.SubFolders;

Once you get a folder collection, creating the folder is pretty much the same except that you specify a ContentTypeId of your custom folder content type. Here is how it looks.

  102             SPFolder folder = documentLibrary.Add("My Folder Name");


  104             // set the content type id and update it, so that the proper attributes are present

  105             folder.Item["ContentTypeId"] = "0x012000521AACBC415A498390B668D81308E454";

  106             folder.Update();

The main thing here is to set the ContentTypeId. As a reminder the base type for a folder is 0x0120 which you have to follow by 00 and a GUID. Most likely, you already have that set up when you built the custom content type, so you can just cut and paste it. This may seem like a simple topic, but as usual with Google, there was not much out there on it. Hopefully, this will help others as they try to do this.

Read the complete post at