In this article I will explain with an example, how to download file as attachment in browser in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following control:
Button – To download the File.
The Button has been assigned with an OnClick event handler.
<asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="Download" />
Downloading the File
When the Download Button is clicked, the Response class properties are set and the path of the file to be downloaded is fetched using Server.MapPath function.
Then, the Content Type of the file is determined using GetMimeMapping method of MimeMapping class and is set in the Response.
Then, the Content-Disposition header is added to the Response which notifies the Browser that the File being downloaded is an Attachment.
Once the Response properties are set, the PDF file contents are read.
Finally, using the WriteFile method of the Response class, the File is written to the Response and the file is downloaded.
C#
protected void Download(object sender, EventArgs e)
{
//Clear the response.
Response.Clear();
//Set the Buffer.
Response.Buffer = true;
//Charset property is appended.
Response.Charset = "";
//Sets the Cache-Control HTTP header.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Fetch the path of the File.
string filePath = Server.MapPath("~/Sample.pdf");
//Determine the name of the File.
string fileName = Path.GetFileName(filePath);
//Determine and set the Content Type of the File.
Response.ContentType = MimeMapping.GetMimeMapping(fileName);
//Specifying that the file is an Attachment.
Response.AddHeader("content-disposition", "attachment; filename=Sample.pdf");
//Writing the File to the Response.
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
VB.Net
Protected Sub Download(ByVal sender As Object, ByVal e As EventArgs)
'Clear the response.
Response.Clear()
'Set the Buffer.
Response.Buffer = True
'Charset property is appended.
Response.Charset = ""
'Sets the Cache-Control HTTP header.
Response.Cache.SetCacheability(HttpCacheability.NoCache)
'Fetch the path of the File.
Dim filePath As String = Server.MapPath("~/Sample.pdf")
'Determine the name of the File.
Dim fileName As String = Path.GetFileName(filePath)
'Determine and set the Content Type of the File.
Response.ContentType = MimeMapping.GetMimeMapping(fileName)
'Specifying that the file is an Attachment.
Response.AddHeader("content-disposition", "attachment; filename=Sample.pdf")
'Writing the File to the Response.
Response.WriteFile(filePath)
Response.Flush()
Response.End()
End Sub
Screenshot
Demo
Downloads