Tuesday, 15 October 2013

How to download a file or image in ASP.NET using C#/VB.NET

Hi friends, in this article I will explain about  How to download a file in ASP.NET using C#/VB.NET.
I already explained in the previous articles about MVC:JQuery UI Datepicker Calender Control In Asp.Net Mvc Application || How to Use jQuery Calender In MVC3Preview image before upload using FileUpload control and jQuery in ASP.NET and How to display SubTotal and Grand Total in ASP.Net GridView using C#/VB.NET

In ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Download"
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


In C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Download : System.Web.UI.Page
{
      protected void Button1_Click(object sender, EventArgs e)
    {
        string filepath = "~/images/loading_image.gif";
        System.IO.FileInfo objFileInfo = default(System.IO.FileInfo);
        objFileInfo = new System.IO.FileInfo(Server.MapPath(filepath));
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + objFileInfo.Name);
        HttpContext.Current.Response.WriteFile(objFileInfo.FullName);
        HttpContext.Current.Response.End();
      
    }
}

In VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class Download
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(sender As Object, e As EventArgs)
        Dim filepath As String = "~/images/loading_image.gif"
        Dim objFileInfo As System.IO.FileInfo = Nothing
        objFileInfo = New System.IO.FileInfo(Server.MapPath(filepath))
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.ContentType = "application/pdf"
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & objFileInfo.Name)
        HttpContext.Current.Response.WriteFile(objFileInfo.FullName)
        HttpContext.Current.Response.[End]()

    End Sub
End Class


 The output will like as shown in the below figure when you click on Download button.

No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.