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

How to get AttachmentFiles when calling GetItemById using Sharepoint CSOM?

我想花点时间记录一个问题,我在使用 .NET 客户端对象模型 (CSOM) 为 Sharepoint 使用 GetItemById 时尝试获取 AttachmentFiles 时解决了这个问题 Microsoft.SharePoint.Client。我找不到这个问题的明确答案。以下是获取 Sharepoint 列表项的基本方法,您可以在 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);

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

正确的做法是:

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