March 15, 2014

Force downloading a file from C #

Force downloading a file from C # 
Many times you want your system to download a pdf file or any file automatically and is not open in the browser either because it is a requirement or our conscience tells us to be like that, whatever the reason I leave here a code for can download any type of file.

This method you will be able to place in any class and download the file regardless of page is called, it can be placed in a Utilities class for example.


public void TheDownload(string path)
  {
      System.IO.FileInfo toDownload =
                 new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));
 
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.AddHeader("Content-Disposition",
                 "attachment; filename=" + toDownload.Name);
      HttpContext.Current.Response.AddHeader("Content-Length",
                 toDownload.Length.ToString());
      HttpContext.Current.Response.ContentType = "application/octet-stream";
      HttpContext.Current.Response.WriteFile(patch);
      HttpContext.Current.Response.End();
  } 




See Also:


Ditulis Oleh : Angelo Hari: 2:26 PM Kategori:

1 comentarios:

  1. When I attempt to implement the above code, the line reading: FileInfo toDownload = new FileInfo(HttpContext.Current.Server.MapPath(path)); throws a NullReferenceException. I have System.IO; included in my using statements.

    Can anyone suggest what may be missing or why this exception is thrown? Or how to get it to work?

    ReplyDelete