Friday, June 20, 2025

How to download the file using handler in asp.net c# of any format or extension

  public void ProcessRequest(HttpContext context)

  {

    if (context.User.Identity.IsAuthenticated)

    {

      string filename = context.Request.QueryString["File"];

      //Validate the file name and make sure it is one that the user may access

      context.Response.Buffer = true;

      context.Response.Clear();

      context.Response.AddHeader("content-disposition", "attachment; filename=" + filename);

      context.Response.ContentType = "application/octet-stream";

//File(HelloWorld.txt) should be present on server in App_Data folder , otherwise it will show error

      context.Response.WriteFile("~/App_Data/" + filename);

    }

  }

aspx page

<a href="MyFileHandler.ashx?File=HelloWorld.txt">Click Here to Get File</a>

No comments:

Post a Comment