开发者

How to get all ContentTypes from a Site Collection in a SharePoint Farm

How to get all ContentTypes from a Site Collection in a SharePoint Farm. R开发者_高级运维emember, I want to do this using the SharePoint Object Model. Any help will be appreciated.


This one will do it for all types in all SPWeb's in a Site. Note this will produce duplicates.

    public void GetContentTypes()
    {
        string siteUrl = "Add site url here";

        using (SPSite site = new SPSite(siteUrl))
        {
                foreach (SPWeb web in site.AllWebs)
                {
                    foreach (SPContentType item in web.ContentTypes)
                    {
                        Debug.WriteLine(item.Name);
                    }
                    foreach (SPList list in web.Lists)
                    {
                        foreach (SPContentType item in list.ContentTypes)
                        {
                            Debug.WriteLine(item.Name);
                        }
                    }
                    web.Dispose();
                }
        }
    }


It can be done like this:

public void ListContentTypes(string siteUrl)
{
  try
  {
    using (SPSite site = new SPSite(siteUrl))
    {
      using (SPWeb web = site.OpenWeb())
      {
        ListContentTypes(web);
      }
    }
  }
  catch (Exception ex)
  {
    // add some proper error handling here
  }
}

public void ListContentTypes(SPWeb web)
{
  foreach (SPContentType ct in web.ContentTypes)
  {
    // do whatever you want to do with the content type here
  }

  foreach (SPWeb subWeb in web.Webs)
  {
    try
    {
      ListContentTypes(subWeb);
    }
    finally
    {
      if (subWeb != null)
      {
        subWeb.Dispose();
      }
    }
  }
}

This will find all content types that exist in the site collection, but remember that not all content types will be available in the entire site collection. For example: if you have a content type 'Product' that exists in a subsite, the code above will find it but you won't be able to use it in the root web because it's defined in a lower level.


Try this one :urWeb.AvailableContentTypes

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜