Download a File from SharePoint Document Library

Introduction 

 
In this blog, you will learn how to download a file from the SharePoint Document Library. 
 
First, you need to write a SharePoint file in your ASP.NET application server with the help of the CopyStream Method. Once you write the SharePoint file in the ASP.NET application server, then the user can download the file easily with the help of the Response.TransmitFile.
 
Here is the complete code to download a file from Sharepoint:
  1. protected void DownloadFile(object sender, EventArgs e) {  
  2.     try {  
  3.         string filePath = (sender as LinkButton).CommandArgument;  
  4.         //SharePoint Credentials  
  5.         string username = "sharepoint_user";  
  6.         string password = "sharepoint_password";  
  7.         var securePassword = new SecureString();  
  8.         foreach(char c in password) {  
  9.             securePassword.AppendChar(c);  
  10.         }  
  11.         var onlineCredentials = new NetworkCredential(username, password, "domain");  
  12.         ClientContext clientContext = new ClientContext(filePath);  
  13.         var url = string.Format("{0}", filePath);  
  14.         string userRoot = System.Environment.GetEnvironmentVariable("USERPROFILE");  
  15.         string downloadFolder = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "Downloads");  
  16.         WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));  
  17.         request.Credentials = onlineCredentials;  
  18.         WebResponse response = request.GetResponse();  
  19.         Stream fs = response.GetResponseStream() as Stream;  
  20.         using(FileStream localfs = System.IO.File.OpenWrite(Server.MapPath("~/Claim_Documents/") + "/" + Path.GetFileName(filePath))) {  
  21.             CopyStream(fs, localfs);  
  22.         }  
  23.         string filename = Path.GetFileName(filePath);  
  24.         Response.ContentType = "application/octet-stream";  
  25.         Response.AppendHeader("Content-Disposition""attachment;filename=" + filename);  
  26.         string aaa = Server.MapPath("~/Claim_Documents/" + filename);  
  27.         Response.TransmitFile(Server.MapPath("~/Claim_Documents/" + filename));  
  28.         Response.End();  
  29.     } catch (Exception ex) {  
  30.         lblmsg.Text = ex.Message;  
  31.     }  
  32. }