0
votes

I wanted to take a moment to document an issue that I resolved when I trying to get the AttachmentFiles while using GetItemById using the .NET Client-Side Object Model (CSOM) for Sharepoint specifically Microsoft.SharePoint.Client. I was unable to find a clear answer to this problem. Here's the basic way to get a Sharepoint List Item which you can find how to do on MSDN any many other sites:

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

I will now post how to correctly include attachments in the answer below:

1

1 Answers

2
votes

Here is the correct way to do it:

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