Last Updated: February 25, 2016
·
1.815K
· arivazhagan

Add Contentype in SharePoint 2013 using c# [CSOM]

Adding a contentype in sharepoint is little trickey for me at the first i cant quite understand it, as always microsoft documentation is really sucks and not complete and so and so.
Code speaks louder than works, so here you go,

public void addContentType(ClientContext context, Web web, String cntTypes)
{
    dynamic cntJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(cntTypes);
    foreach (var ctItem in cntJSON)
    {
        ContentTypeCollection ContType = web.ContentTypes;
        ContentTypeCreationInformation msnContType = new ContentTypeCreationInformation();
        msnContType.Name = ctItem.Name;
        msnContType.Description = ctItem.Description;
        msnContType.Group = ctItem.Group;
        if (ctItem.Type == "docset")
        {
            msnContType.ParentContentType = web.ContentTypes.GetById("0x0120D520");
        }
        ContentType newCntType = ContType.Add(msnContType);
            context.ExecuteQuery();
            web.Update();
            Console.WriteLine(ctItem.Name + " content type created  successfully");
        }
    }
}

let me break it down the process for you,

  1. ContentTypeCollection - Holds site content Type collection as below

    ContentTypeCollection siteContType = web.ContentTypes;
  2. ContentTypeCreationInformation - Holds the newly creating content type information like name,description and other properties.

  3. create new content type with ContentTypeCreationInformation as below

    ContentTypeCreationInformation newContType = new ContentTypeCreationInformation();
  4. Then add the required properties as below,

    msnContType.Name = "IronMan";
    msnContType.Description = "Tony Stark Inc.";
    msnContType.Group = "Super Heros";
  5. If you want to create docset content type you need to add the ParentContentType as below,

    newContType.ParentContentType = web.ContentTypes.GetById("0x0120D520");

    FYI 0x0120D520 is the id of docset contenttype.

  6. Add newly created contentype to site content type collection as below

    ContentType newCntType = ContType.Add(msnContType);
  7. Save your changes,

    context.ExecuteQuery();
    web.Update();

Feel free to share if you think there is a better way to add content types.