Wednesday, July 22, 2015

Download file from SharePoint document library C#

Download File from SharePoint Document Library C#

Lets see how to download a file from SharePoint document library 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. We can use the explorer view, if it is a few files or if it is a complete folder or all the files in the document library. However, if we want to customize the query or automate the process, then we can use the below C# code to download the files programmatically.

  1. 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
}
}
  1. Access the document library using the web object from the above step.
// get the required document library SPList
docLib = web.Lists["Shared Documents"];
  1. 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.

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

** original post at http://ift.tt/1LD33pT - The SharePoint Guide


by Prashanth Padebettu via Everyone's Blog Posts - SharePoint Community

No comments:

Post a Comment