aspnet
  1. aspnet-download-file

Download File - ( ASP.NET Web Forms )

Downloading files from a webserver is a common requirement in web applications. In ASP.NET Web Forms, you can provide users with the ability to download files by adding a hyperlink or button to your web form.

Syntax

The syntax for downloading a file in ASP.NET Web Forms is as follows:

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();

Example

Here's an example of how to use the download file feature in ASP.NET Web Forms:

protected void DownloadButton_Click(object sender, EventArgs e)
{
    string fileName = "example.pdf";
    string filePath = Server.MapPath("~/Files/example.pdf");

    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.TransmitFile(filePath);
    Response.End();
}

Output

When a user clicks the download button on the webform, the file is downloaded to their local machine. The user can then open or save the file from their local machine.

Explanation

The above code sets the content type of the response to "application/octet-stream". The Content-Disposition header specifies the filename of the file to be downloaded and sets its disposition type to attachment.

The TransmitFile method allows the server to transmit the content of a file to the client and terminates the connection afterwards. The End method stops execution of the current page.

Use

The download file feature is useful for web applications that allow users to download files from a server.

Important Points

  • Set the content type to "application/octet-stream" when downloading a file
  • Provide the filename in the Content-Disposition header
  • Use the TransmitFile method to send the file content to the client
  • Call the End method to stop executing the current page.

Summary

In this page, we learned how to download files in ASP.NET Web Forms. We discussed the syntax, example, output, explanation, use, and important points of downloading files in ASP.NET Web Forms. By adding a hyperlink or button, you can allow users to download files from servers.

Published on: