Download document from document library using client object model


Here I will explain you how to download documet from document library using client object model. We can download document from a particular item and also you can download all items from the document library.


Also, have a look at below articles:

How to get list item attachments using JavaScript client object model?

Download a FREE PDF on SharePoint online tutorial

Work with SPServices in SharePoint 2013

Below is the code to download document from a particular item:

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

}

Below is the code for download all the document library using 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);
}
}
}



Hope this will be helpful to you.

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →