【问题标题】:How to get all ContentTypes from a Site Collection in a SharePoint Farm如何从 SharePoint 场中的网站集中获取所有 ContentType
【发布时间】:2011-06-01 01:34:37
【问题描述】:

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

【问题讨论】:

    标签: sharepoint content-type


    【解决方案1】:

    这将适用于站点中所有 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();
                    }
            }
        }
    

    【讨论】:

    • 我必须查看所有网站,而不仅仅是 rootweb!
    • 您需要对使用 site.AllWebs 获得的每个 SPWeb 进行处理
    • 这应该返回所有的 SITE 内容类型,但它也不会得到所有的 LIST 内容类型。我想不出你为什么要这样做,但值得认识到差异。 novolocus.com/2008/03/28/content-types-whos-your-daddy
    • @Andy,感谢您的评论,我已经更新了代码以遍历列表。
    • 我已经测试了代码,很抱歉它是一个无限循环!
    【解决方案2】:

    可以这样做:

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

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

    【讨论】:

      【解决方案3】:

      试试这个:urWeb.AvailableContentTypes

      【讨论】:

      • 它是否包括所有可用的已安装 ContentTypes selected/non-selected 和 used/non-used?
      • 这个属性的问题是它不会给你在较低级别定义的内容类型。因此它不会从网站集中返回所有内容类型。它为您提供在特定网站及其所有父网站中定义的内容类型。
      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      相关资源
      最近更新 更多