Search This Blog

Tuesday, June 13, 2017

How to download files from SharePoint document library programmatically using C#

Sometimes, we would want to download multiple files based on a pre-defined query such as a monthly report or a bulk download.
If it is a few files or if it is a complete folder, we can use the explorer view to copy paste the files. However, if we want to customize the query or automate the process, then we need to write custom code to download the files programmatically. This is also true, if we want to access the metadata of the files along with downloading the actual files.

Use the standard object model to access the SharePoint site and web.
string siteUrl = "site url";
using(SPSite site = new SPSite(siteUrl)
{
  using(SPWeb web = site.OpenWeb())
  {
    // code to download documents
  }
}
Retrieve the document library object using the SPWeb object from the above step.
// get the required document library
SPList docLib = web.Lists["Shared Documents"];
Access the items to be downloaded and download the files.
// loop through each item or document in the document library
foreach(SPListItem item in docLib.Items)
{
  // Access the file
  SPFile file = item.File;
  if(file != null)
  {
    // retrieve the file as a byte array
    byte[] bArray = file.OpenBinary();
    string filePath = Path.Combine("c:\\temp", file.Name);
    //open the file stream and write the file
    using(FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
    {
      fs.Write(bArray, 0, bArray.Length);
    }
  }
}
The above server side code can be used if you are using page code behind, event handler, timer job etc. I will do another post for downloading the documents from client side such a console application or a windows application.
In case you do not want to download all the files, you can use CAML query to filter the items in a document library or even a site collection and loop through those items. If it is spanning multiple site collections, you can use search query to retrieve the items.
Instead of using the file object from the SharePoint item, we can also use the file url to download the file from the document library. Following code will download the file located at url fileUrl to C:\Docs folder locally on the server:
FileStream fstream = null;
string fileName = Path.GetFileName(fileUrl);
if (!string.IsNullOrEmpty(fileName))
{
  byte[] data;
  byte[] buffer = new byte[2048];
  WebRequest request = WebRequest.Create(url);
  using (WebResponse response = request.GetResponse())
  {
    using (Stream responseStream = response.GetResponseStream())
    {
      using (MemoryStream ms = new MemoryStream())
      {
        int count = 0;
        do
        {
          count = responseStream.Read(buffer, 0, buffer.Length);
          ms.Write(buffer, 0, count);
        } while (count != 0);
        data = ms.ToArray();
      }
    }
  }
  string filePath = "C:\Docs";
  using (fstream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
  {
    fstream.Write(data, 0, data.Length);
    fstream.Close();
  }
}

No comments:

Post a Comment