Download documents from Document Library using SharePoint Server Object Model


Here we will discuss how we can download documents from SharePoint 2013 document library using server-side object model. Previously article, I have explained how we can download documents using the client-side object model.


Also check out:
– Alternative way to promote people picker in infopath form library in SharePoint 2013

– Create Update Delete a list using Client Object Model CSOM in SharePoint 2013

– Hide left navigation using jQuery in SharePoint 2013

Below is the full code:

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySP2013
{
class DownloadDocumentFromDocumentLibrary
{
String siteURL = “http://SiteURL:12345/sites/Employee”;
//String listName = “Employee”;
string folderpath = @”C:\Download”;

public void DownloadDocumentFromDocLibrary()
{
string downloadItemLocation = string.Empty;

using (SPSite site = new SPSite(siteURL)) // Site Collection
{
using (SPWeb web = site.OpenWeb()) // Site
{
SPList list = web.Lists[“EmployeeDocuments”];

foreach (SPFile file in list.RootFolder.Files)
{
DownloadFileUsingFileStream(file, folderpath);

}
}
}
}

private void DownloadFileUsingFileStream(SPFile file, string path)
{
byte[] filecontent = file.OpenBinary();

FileStream fs = new FileStream(path +”\\”+ file.Name, FileMode.CreateNew);

using (fs)
{

BinaryWriter bw = new BinaryWriter(fs);

bw.Write(filecontent, 0, filecontent.Length);

bw.Close();

}

}
}
}



Hope this will be helpful.

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 →