如何在 C# 中调用 Sharepoint 分类法

How to Call Sharepoint Taxonomy in C#

我有以下 PowerShell,其中 returns 存储在 SharePoint 托管元数据中的所有部门的列表:

Add-PSSnapin Microsoft.Sharepoint.Powershell

# Get the site collection
$sitecollection = Get-SPSite 'http://mysharepointsite/'

# Get the term store id
$taxsession = Get-SPTaxonomySession -Site $sitecollection

# Change to the requierd service name
$termstore = $taxsession.TermStores["Managed Metadata Service"] 
$termstore.id

# Get the term set id
$termstoregroup = $termstore.Groups["People"]
# Change to your term set name
$termset = $termstoregroup.TermSets["Department"]
$termset.id

$departments = $termset.id.name

我需要使用 C# 来实现相同的目的,但我找不到适合我的东西。有谁知道这里的标准方法是什么?

我总是可以从我的 C# 应用程序内部开始 PowerShell 会话,但这似乎是一种非常迂回的方式来做一些 C# 应该没有问题的事情。

我设法从 C# 使用以下代码做到了这一点:

var spSite = new SPSite(@"http://mysharepointsite/");

var taxSession = new TaxonomySession(spSite);

var termStore = taxSession.TermStores["Managed Metadata Service"];
var termStoreGroup = termStore.Groups["People"];
var termSet = termStoreGroup.TermSets["Department"];

var deps = termSet.Terms;

foreach (var dep in deps)
{
    MessageBox.Show(dep.Name);
}

这与主要问题中的几乎相同。

重要的是不要让此代码仅在安装了 SharePoint 的服务器上运行。当 运行 在我的常规开发机器上执行此操作时,我在第 1 行收到此异常:

An unhandled exception of type 'System.TypeInitializationException' occurred in Microsoft.SharePoint.dll

Additional information: The type initializer for 'Microsoft.SharePoint.CoreResource' threw an exception.

同样,我只能 运行 来自 SharePoint 服务器问题的 PowerShell 脚本 - 这很有意义,因为它们似乎使用相同的 .Net 对象,即 TaxonomySession


使用 this sample,我还可以使用以下代码从我自己的计算机 中检索部门列表

var clientContext = new ClientContext("http://mysharepointsite/")
    { AuthenticationMode = ClientAuthenticationMode.Default};

var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
var termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
clientContext.Load(termStore,
        store => store.Name,
        store => store.Groups.Include(
            group => group.Name,
            group => group.TermSets.Include(
                termSet => termSet.Name,
                termSet => termSet.Terms.Include(
                    term => term.Name)
            )
        )
);
clientContext.ExecuteQuery();

if (taxonomySession != null)
{
    if (termStore != null)
    {
        foreach (var termGroup in termStore.Groups)
        {
            foreach (var termSet in termGroup.TermSets)
            {
                foreach (var term in termSet.Terms)
                {
                    MessageBox.Show(term.Name);
                }
            }
        }
    }
}

正如 Murray Foxcroft 提到的,这利用了客户端对象模型 (CSOM),它允许我们远程访问分类。

在 SharePoint 世界中,服务器和客户端库的名称相同,即Microsoft.Sharepoint.dll 但有不同的实现,这会使事情变得混乱并给出您遇到的错误。如果你需要从服务器 运行 然后你可以继续你有什么。如果您需要远程 运行,那么您将需要移植到我的回答中提供的 CSOM(客户端对象模型)。

它会泄漏。SPSite 实现了 IDisposbale 接口...既然您创建了资源,您就需要处理它。最简单的方法是使用 using 结构。

using(SPSite site = new SPSite("http://server"))
{
}