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:
- 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;
- }
- }

Polo TEcsonPosted Jan 27, 2022, 11:33 AM
Visual Studio can't seem to recognize Server, CopyStream(), and Response variables from your code. Do those require certain assemblies?
Talha ManzoorPosted Aug 29, 2020, 11:52 AM
You can find me on blogger https://www.talhamanzoor2.blogspot.com