0

I want to serve a dynamically created binary file from an asp.net web page via a http request parameter like so: www.host.com/?Download=file. So far I have

protected void Page_Load(object sender, EventArgs e)
{
  if (Request.Params.Allkeys.Contains("Download"))
  {
    String fileStr = Request.Params.GetValues("Download")[0];

    using (Stream generatedFile = File.Create(@"C:\Temp\file"))
    {
      /* write the contents of the file */
    }

    Response.ContentType = "application";
    Response.AddHeader("Content-Disposition",
                       "attachment; filename=" + fileStr);
    Response.WriteFile(@"C:\Temp\file");
    Response.End();
  }
}

which works, but C:\Temp\file still exists and I'd like it cleaned up. Calling File.Delete(@"C:\Temp\file"); after Response.End() doesn't work, since Response.End() kills the thread. Putting the Response methods inside the using block, with File.Create( (...), FileOptions.DeleteOnClose) doesn't work, since the Response methods then fail to get access to the file.

Any suggestions?

NiloCK
  • 571
  • 1
  • 11
  • 33

1 Answers1

1

After writing file to response you can call Response.Flush to make sure it was fully written, and then delete it before calling Response.End:

Response.WriteFile(@"C:\Temp\file");
Response.Flush();
File.Delete(@"C:\Temp\file");
Response.End();
Andrei
  • 55,890
  • 9
  • 87
  • 108