Add ContentType to pages library

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            List<string> listContentType = new List<string>();
            listContentType.Add("CT_TestContentType1");
            listContentType.Add("CT_TestContentType2");



            SPSite currentSite = (SPSite)properties.Feature.Parent;
            SPWebCollection webColl = currentSite.AllWebs;
            foreach (SPWeb web in webColl)
            {
                try
                {
                    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                    SPList pagelibrary = publishingWeb.PagesList;
                    if (pagelibrary != null)
                    {
                        try
                        {
                            SPField field = pagelibrary.Fields["IsProtected"];
                        }
                        catch
                        {
                            pagelibrary.Fields.Add("IsProtected", SPFieldType.Boolean, false);
                            SPFieldBoolean fIsProtected = (SPFieldBoolean)pagelibrary.Fields["IsProtected"];
                            fIsProtected.DefaultValue = "0";
                            fIsProtected.Update();
                        }

                        pagelibrary.ContentTypesEnabled = true;
                      
                        for (int i = 0; i < listContentType.Count; i++)
                        {
                            SPContentType contentType = web.AvailableContentTypes[listContentType[i].ToString()];
                            if (contentType != null)
                            {
                                if (pagelibrary.IsContentTypeAllowed(contentType) && pagelibrary.ContentTypes[contentType.Name] == null)
                                {
                                    pagelibrary.ContentTypes.Add(contentType);
                                }
                            }
                        }
                    }
                }
                catch
                { }
            }
        }

  

原文地址:https://www.cnblogs.com/dexter2003/p/2694436.html