Download a file from SharePoint document library | download a file from sharepoint document library c#
Introduction
In this blog, you will learn how to download a file from the SharePoint Document Library ASP.NET web application.
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:
- protected void DownloadFile(object sender, EventArgs e) {
- try {
- string filePath = (sender as LinkButton).CommandArgument;
- //SharePoint Credentials
- string username = "sharepoint_user";
- string password = "sharepoint_password";
- var securePassword = new SecureString();
- foreach(char c in password) {
- securePassword.AppendChar(c);
- }
- var onlineCredentials = new NetworkCredential(username, password, "domain");
- ClientContext clientContext = new ClientContext(filePath);
- var url = string.Format("{0}", filePath);
- string userRoot = System.Environment.GetEnvironmentVariable("USERPROFILE");
- string downloadFolder = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "Downloads");
- WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
- request.Credentials = onlineCredentials;
- WebResponse response = request.GetResponse();
- Stream fs = response.GetResponseStream() as Stream;
- using(FileStream localfs = System.IO.File.OpenWrite(Server.MapPath("~/Claim_Documents/") + "/" + Path.GetFileName(filePath))) {
- CopyStream(fs, localfs);
- }
- string filename = Path.GetFileName(filePath);
- Response.ContentType = "application/octet-stream";
- Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
- string aaa = Server.MapPath("~/Claim_Documents/" + filename);
- Response.TransmitFile(Server.MapPath("~/Claim_Documents/" + filename));
- Response.End();
- } catch (Exception ex) {
- lblmsg.Text = ex.Message;
- }
- }