How can I use a content type programmatically?

example: I have a content type called "Doc Template1" and I have added it as a content type in my document library. And when I click New Document > Doc Template1; Microsoft Word opens up.

Now, how will I do this programmatically?

I have now retrieve my content types using

foreach (SPContentType cType in contentTypeCollection)

{ lstBox.Items.Add(cType.Name); }


3 Answers 3


You need only change field value as in follow code.

item[SPBuiltInFieldId.ContentType] = "Content Type ID";

One way to get the content types of a specific document library is to access these via SPList.ContentTypes which returns a collection of the associated content types to that specific list or library. You can use it like so:

using (var site = new SPSite("http://somesharepointsite.com"))
   var web = site.RootWeb;
   var list = web.Lists["Some Library"];
   var contentTypeCollection = list.ContentTypes;
   // place your code here...

Instantiating a new site collection (with the SPSite) contructor is quite time and memory consuming. So if your situation allows it you should rahter use the SPContext.Current.Site or SPContext.Current.Web properties.


it's not so difficult.

     SPList docLib; //found your document liberary;

     docLib.ContentTypes.Add(web.ContentTypes.OfType<SPContentType>().Where(c => c.Name.Equals("Doc Template1", StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
  • I am currently trying your code. but where can I get .OfType ?
    – Aventus
    Commented Mar 15, 2012 at 23:55
  • 1
    .OfType is part of Linq extension methods. the namespace is: System.Linq Commented Mar 17, 2012 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.