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?