Index

Downloading a File with a Save As Dialog in ASP.NET

Most Web applications involve file transfers between the client and the server.
The following example is a common practice of file downloading using ASP.Net & C#.

Downloading a file in ASP.NET is straightforward and does not require you to copy the file byte-by-byte to the response page
Create the button using following code in your download.aspx file

asp:Button ID="btnDownload" Text="Click here to download" OnClick="btnDownload_Click" runat="server"

Add the following code in your download.aspx.cs
public void btnDownload_Click(object source, EventArgs e)
{
 // Make sure this to be absolute path
 string strFileName = "~/test.txt";
 downloadFile(strFileName);
}

// Will show the save as dialog.
protected void downloadFile(string strFilename)
{
 FileInfo fileInfo = new FileInfo(strFilename);

 if (fileInfo.Exists)
 {
  Response.Clear();
  Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
  Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  // The following examples set the ContentType property to other common values.
  // Response.ContentType = "text/HTML"
  // Response.ContentType = "image/GIF"
  // Response.ContentType = "image/JPEG"
  // Response.ContentType = "text/plain"
  // Response.ContentType = "image/JPEG"
  Response.ContentType = "application/x-cdf";
  Response.TransmitFile(Server.MapPath(strFilename));
  Response.End();
 }
}

// Will open the file on the screen.
protected void writeToScreen(string strFilename)
{
 FileInfo fileInfo = new FileInfo(strFilename);

 if (fileInfo.Exists)
 {
  Response.Clear();
  Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
  Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  Response.ContentType = "application/octet-stream";
  Response.Flush();
  Response.WriteFile(fileInfo.FullName);
 }
}

Index