问题描述
我可以编辑其他字段,如标题,甚至是我自己创建的字段,但我不知道如何将关键字添加到我上传的文档中.这是我到目前为止.我得到的错误说关键字列不存在.关键字字段类型是托管元数据.这是我想要将关键字添加到 这里是我想要添加的位置的图像关键词转化为
I can edit other fields like Title and even my own created fields, but I cant figure out how to add in Keywords to a document I upload. This is what I have so far. The error I get says that the Keywords column does not exist. The Keywords fields type is Managed Metadata. Here is a image of where I want to add keywords into Here is a image of where I want to add keywords into
更新:这是有效的更新代码
Update: Here is the updated code of what worked
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();
}
}
推荐答案
这是一个分类字段,因此首先您必须从托管元数据存储中获取关键字:
It's a taxonomy field so first you have to get your keywords from the managed metadata store:
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 类中的方法设置字段:
Then set field using method contained in TaxonomyField class:
var taxonomyField = context.CastTo<TaxonomyField>(list.Fields.GetByInternalNameOrTitle("Keywords"));
context.Load(taxonomyField);
context.ExecuteQuery();
taxonomyField.SetFieldValueByCollection(item, collection, store.DefaultLanguage);
item.Update();
context.ExecuteQuery();
这篇关于如何使用 c# 在 SharePoint 中编辑关键字字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!