如何从SharePoint场中的网站集中获取所有ContentTypes

时间:2010-12-29 13:22:58

标签: sharepoint content-type

如何从SharePoint场中的网站集获取所有ContentTypes。请记住,我想使用SharePoint对象模型执行此操作。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

这个将针对站点中所有SPWeb的所有类型执行此操作。请注意,这将产生重复。

    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();
                }
        }
    }

答案 1 :(得分:3)

可以这样做:

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();
      }
    }
  }
}

这将找到网站集中存在的所有内容类型,但请记住,并非所有内容类型都可用于整个网站集。例如:如果您有一个子网站中存在的内容类型“产品”,上面的代码将找到它,但您将无法在根网站中使用它,因为它是在较低级别定义的。

答案 2 :(得分:2)

试试这个:urWeb.AvailableContentTypes