SharePoint 2013/2016: Download documents from document library programmatically

This SharePoint CSOM tutorial explains, how to download documents from SharePoint 2013/2016 document library using the client object model. We will see, how to download documents from a particular list item and also you to download all items from a SharePoint document library.

SharePoint download documents from document library programmatically

Below is the SharePoint client object model code to download documents from a particular SharePoint list item:

You can write a console application and windows forms application to test the code.

public void DownloadDocumentFrmDocumentLibrary()
{

ClientContext context = new ClientContext(siteURL);
context.Credentials = new System.Net.NetworkCredential(userName, password);
Web web = context.Web;
List list = web.Lists.GetByTitle(documentLibraryName);

ListItem listItem = list.GetItemById(9);
context.Load(list);
context.Load(listItem, i => i.File);
context.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
var fileName = Path.Combine(filePath, (string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}

}

Download all items from a SharePoint document library programmatically

Below is the code for download all the documents from a SharePoint document library using the client object model:

public void DownloadDocumentFrmDocumentLibrary()
{

ClientContext context = new ClientContext(siteURL);
context.Credentials = new System.Net.NetworkCredential(userName, password);
Web web = context.Web;
List list = web.Lists.GetByTitle(documentLibraryName);

CamlQuery query = new CamlQuery();
ListItemCollection items = list.GetItems(query);
context.Load(items);
context.ExecuteQuery();

foreach (ListItem listItem in items)
{
context.Load(listItem, i => i.File);
context.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
var fileName = Path.Combine(filePath, (string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
}

You may like following SharePoint tutorials:

This SharePoint CSOM tutorial, we learned how to download documents from a document library using the SharePoint client object model. How to download documents from a particular item as well as how to download all the documents from a SharePoint document library.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>