共用方式為


Programmatically Creating a SharePoint Content Type

I have been working on a project that requires creating a content type programmatically.  Admittedly, it took me awhile to figure it out.  You can create a content type for SharePoint declaratively in a feature using XML similar to the following:

 <?xml version="1.0" encoding="utf-8"?>
<Elements Id="2fdb55a0-75c1-4ad4-b709-82b2e1393f34"
          xmlns="https://schemas.microsoft.com/sharepoint/">
  <ContentType ID="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2
007948130EC3DB064584E219954237AF39
0075425CE93BDC404F8B042629FC235785"                   
               Name="TermsAndConditionsType"
               Group="Custom Content Types"
               Description="Custom Content Type for Terms and Conditions">
    <FieldRefs>
      <FieldRef ID="{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8}"
                Name="PublishingPageContent" />
    </FieldRefs>
  </ContentType>
</Elements>

That really long ID that is broken into three lines needs to be on a single line, it was formatted for readability.  The challenge is that when we try to delete the content type, we get an error that the content type is part of an application and cannot be deleted.  So, I needed to instead create the content type programmatically.

The above XML works out to the following code:

 using (SPSite site = new SPSite("https://sp2010dev:44365"))
{
    SPWeb web = site.RootWeb;
                
    HtmlField field = (HtmlField)web.Fields["Page Content"];

    SPContentTypeId id = new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2
007948130EC3DB064584E219954237AF39
0075425CE93BDC404F8B042629FC235785");
    SPContentType termsAndConditionsType = new
        SPContentType(
            id,            
            web.ContentTypes,
            "TermsAndConditionsType");
                
    web.ContentTypes.Add(termsAndConditionsType);
    termsAndConditionsType = web.ContentTypes[id];
    termsAndConditionsType.Group = "Custom Content Types";
    termsAndConditionsType.Description = "Custom Content Type for Terms and Conditions";
    termsAndConditionsType.Update();
    SPFieldLink l = new SPFieldLink(field) { DisplayName = "Page Content" };
    termsAndConditionsType.FieldLinks.Add(l);
    termsAndConditionsType.Update();                
}

Again, the really long string needs to be in a single line.

Comments

  • Anonymous
    July 01, 2015
    This HtmlField from where is comming?