For legacy Web Forms applications, you must manually manipulate the Response object to push the file to the client's browser.
In modern ASP.NET Core applications, the built-in File() method is the most straightforward way to serve documents. This method automatically handles setting the correct headers for you. download document in asp.net c#
Efficiently managing file downloads is a core requirement for many modern web applications. Whether you are building an intranet document portal or a customer-facing invoice system, knowing how to requires understanding different framework patterns and security best practices. 1. Simple Document Download in ASP.NET Core (MVC/Web API) For legacy Web Forms applications, you must manually
protected void btnDownload_Click(object sender, EventArgs e) { string filePath = Server.MapPath("~/App_Data/Reports/ProjectSummary.pdf"); Response.Clear(); Response.ContentType = "application/pdf"; // 'attachment' forces a download dialog; 'inline' attempts to open in browser Response.AddHeader("Content-Disposition", "attachment; filename=ProjectSummary.pdf"); Response.WriteFile(filePath); Response.Flush(); Response.End(); } Use code with caution. 3. Key Best Practices for Security and Performance Efficiently managing file downloads is a core requirement
Serving files directly from your server exposes you to potential risks. Implement these strategies to ensure a professional, secure implementation: ASP.NET MVC Uploading and Downloading Files - Mike Brind
[HttpGet] public IActionResult DownloadDocument(string fileName) { // 1. Locate the physical path of the file var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/documents", fileName); if (!System.IO.File.Exists(filePath)) return NotFound(); // 2. Open the file as a stream for efficient memory usage var stream = System.IO.File.OpenRead(filePath); // 3. Return the file with a MIME type and the original file name return File(stream, "application/octet-stream", fileName); } Use code with caution. 2. Downloading Files in ASP.NET Web Forms