如何使用c#编辑SharePoint中的关键字字段?

时间:2017-05-30 17:52:10

标签: c# sharepoint

我可以编辑其他字段,例如Title,甚至我自己创建的字段,但我无法弄清楚如何将关键字添加到我上传的文档中。这就是我到目前为止所拥有的。我得到的错误表明关键字列不存在。关键字字段类型是托管元数据。以下是我要在Here is a image of where I want to add keywords into

中添加关键字的图片

更新:这是更新的代码

    static void AddMetaData(ClientContext ctx, string fName, string kWords )
    {
        List list = ctx.Web.Lists.GetByTitle("Documents");
        ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());
        ctx.Load(items); // loading all the fields
        ctx.ExecuteQuery();

        TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);
        var store = session.GetDefaultKeywordsTermStore();
        var terms = store.KeywordsTermSet.GetAllTerms();
        ctx.Load(store, i => i.DefaultLanguage);
        ctx.ExecuteQuery();

        var collection = new System.Collections.ObjectModel.Collection<Term>();
        var keywords = kWords.Split(';');
        foreach (var key in keywords)
        {
            var filtered = ctx.LoadQuery(terms.Where(t => t.Name == key));
            ctx.ExecuteQuery();
            var term = filtered.SingleOrDefault();
            if (term != null)
                collection.Add(term);
        }

        foreach (var item in items)
        {
            var taxonomyField = ctx.CastTo<TaxonomyField>(list.Fields.GetByInternalNameOrTitle("Keywords"));
            ctx.Load(taxonomyField);
            ctx.ExecuteQuery();
            taxonomyField.SetFieldValueByCollection(item, collection, store.DefaultLanguage);
            item.Update();
            ctx.ExecuteQuery();
        }
    }

1 个答案:

答案 0 :(得分:1)

这是一个分类法字段,因此首先必须从托管元数据存储中获取关键字:

TaxonomySession session = TaxonomySession.GetTaxonomySession(context);
var store = session.GetDefaultKeywordsTermStore();
var terms = store.KeywordsTermSet.GetAllTerms();
context.Load(store, i => i.DefaultLanguage);
context.ExecuteQuery();

var collection = new System.Collections.ObjectModel.Collection<Term>();
var keywords = new string[] { "Key1", "Key2" };
foreach (var key in keywords)
{
    var filtered = context.LoadQuery(terms.Where(t => t.Name == key));
    context.ExecuteQuery();
    var term = filtered.SingleOrDefault();
    if (term != null)
        collection.Add(term);
}

然后使用TaxonomyField类中包含的方法设置字段:

var taxonomyField = context.CastTo<TaxonomyField>(list.Fields.GetByInternalNameOrTitle("Keywords"));
context.Load(taxonomyField);
context.ExecuteQuery();
taxonomyField.SetFieldValueByCollection(item, collection, store.DefaultLanguage);
item.Update();
context.ExecuteQuery();