如何使用Sharepoint CSOM调用GetItemById时获取AttachmentFiles?

时间:2017-02-01 19:54:03

标签: sharepoint csom

我想花一点时间来记录我在使用GetItemById使用GetItemById时使用.NET客户端对象模型(CSOM)专门为Microsoft.SharePoint.Client获取AttachmentFiles时解决的问题。我无法找到这个问题的明确答案。以下是获取Sharepoint List项目的基本方法,您可以在MSDN上找到如何处理任何其他网站:

var siteUrl = "http://MyServer/sites/MySiteCollection";

var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var targetList = site.Lists.GetByTitle("Announcements");

var targetListItem = targetList.GetItemById(4);

clientContext.Load(targetListItem, item => item["Title"]);
clientContext.ExecuteQuery();

Console.WriteLine("Retrieved item is: {0}", targetListItem["Title"]);

// This will throw an AttachmentFiles "Not Initialized" Error
Console.WriteLine("AttachmentFiles count is: {0}", targetListItem.AttachmentFiles.Count);

我现在将在下面的答案中发布如何正确包含附件:

1 个答案:

答案 0 :(得分:2)

这是正确的方法:

var siteUrl = "http://MyServer/sites/MySiteCollection";

var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var targetList = site.Lists.GetByTitle("Announcements");

var targetListItem = targetList.GetItemById(4);
var attachments = targetListItem.AttachmentFiles;

clientContext.Load(targetListItem, item => item["Title"]);
clientContext.Load(attachments)
clientContext.ExecuteQuery();

Console.WriteLine("Retrieved item is: {0}", targetListItem["Title"]);   
// This will no longer throw the error 
Console.WriteLine("AttachmentFiles count is: {0}", targetListItem.AttachmentFiles.Count);
相关问题