2

I'm using the CSOM to get my SharePoint list. I need to loop through it and get the URLs for the files attached to each item in the list.

C#:

SPContext spctx = new SPContext("news");

List news = spctx.getList("News");

ListItemCollection lc = spctx.getListItems(news);

for (int i = 0; i < lc.Count; i++)
{
    AttachmentCollection attachments = lc[i].AttachmentFiles;
    for (int j = 0; j < attachments.Count; j++)
    {
        var test = attachments[j];
    }
}
2

Here is the pseudo code you can use

foreach (ListItem listItem in items)
{
    Folder folder = oWeb.GetFolderByServerRelativeUrl(oSite.Url + "/Lists/"+listName+/Attachments/" + listItem["ID"]);
    clientContext.Load(folder);

    try
    {
        clientContext.ExecuteQuery();
    }
    catch (ServerException ex)
    {

    }
    FileCollection attachments = folder.Files;
    clientContext.Load(attachments);
    clientContext.ExecuteQuery();

    foreach (Microsoft.SharePoint.Client.File oFile in folder.Files)
    {
        //oFile.ServerRelativeUrl - Contains the attachment URL
    }
}
  • I've updated my question. To clarify I'm stuck trying to get the URLs from the AttachmentCollection. – matt Nov 26 '14 at 16:24
2

The following example demonstrates how to retrieve all attachments for list items using CSOM:

//Retrieve list items attachments 
var list = ctx.Web.Lists.GetByTitle(listTitle);
var items = list.GetItems(CamlQuery.CreateAllItemsQuery()); 
ctx.Load(items, icol => icol.Include(i => i["Title"], i => i.AttachmentFiles));
ctx.ExecuteQuery();

//Print attachment Urls for list items
foreach (var item in items)
{
     if (item.AttachmentFiles.Count > 0)
     {
        Console.WriteLine("{0} attachments:", item["Title"]);
        foreach (var attachment in item.AttachmentFiles)
        {
            Console.WriteLine(attachment.ServerRelativeUrl);
        }
     }
     else
     {
          Console.WriteLine("For {0} list item no attachments were found", item["Title"]);
     }
 } 
  • I actually wrote this in my code but without the title inclusion. Calling ctx.ExecuteQuery() gives me a "Value does not fall within expected range" error. What could that mean? None of the list items have attachments yet. – Dinerdo Oct 31 '15 at 3:35
  • 1
    @Dinerdo, do you mind to post a separate question with your example, i would be glad to take a look – Vadim Gremyachev Oct 31 '15 at 18:41
  • 1
    I posted the question. I believe I figured out a way to make it work, but my question now is about choosing the best efficiency: sharepoint.stackexchange.com/questions/161159/… – Dinerdo Oct 31 '15 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.