Download a document from SharePoint Document Library using CSOM 2013

Hello Readers,

In this article, I will share a piece of code to download a  document from a document library using Client Side Object Model. Sharepoint is moving more towards Client Side Object model than Server side code for faster execution. As we move more towards next verison – SharePoint 2016, there is a heavy emphasis on Client side Code. This article talks about uploading a document into document library with the metadata values as well.

// Setting Client Context for the Download operation

SP.ClientContext ctx = new SP.ClientContext(“http://mysite/site”);

Web web = ctx.Web;

var list = ctx .Web.Lists.GetByTitle(“EmployeeDocuments”);
var listItem = list.GetItemById(listItemId);
ctx .Load(list);
ctx .Load(listItem, name => name.File);
ctx .ExecuteQuery();

//Get the File Information

var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var Name = Path.Combine(“D:”,(string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(Name))
{
fileInfo.Stream.CopyTo(fileStream);
}

Please read my blog to upload a document to a document library using CSOM.

Happy SharePointing :-)

Leave a Reply

Your email address will not be published.