1

I have a scenario where I have been able to get the file that I want to download using a CAML query. I am using client object model approach. I need to save this file locally. Please guide how can I achieve this?

2

Based on my research and past experience this could be an approach to download files from a SharePoint Document Library.

First you get connected to the SharePoint site, and retrieve using list.GetItemById(ID) function.

Once you load item object, you can get the Server Relative Url of the file. And from this Url you can download the document.

You can read How to download/upload files from/to SharePoint 2013 using CSOM?

using (var clientContext = new ClientContext(url))
{

    var list = clientContext.Web.Lists.GetByTitle(listTitle);
    var listItem = list.GetItemById(listItemId);
    clientContext.Load(list);
    clientContext.Load(listItem, i => i.File);
    clientContext.ExecuteQuery();

    var fileRef = listItem.File.ServerRelativeUrl;
    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
    var fileName = Path.Combine(filePath,(string)listItem.File.Name);
    using (var fileStream = System.IO.File.Create(fileName))
    {                  
        fileInfo.Stream.CopyTo(fileStream);
    }
}

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.