Reputation: 584
I am writing an application where the user will generate files which the user can view and then choose to download if it look OK. The application writes the file to server in the following way:
private void WriteTestFileToServer(MyFile file)
{
string serverPath = "~/MyFiles";
string fileName = "/FileExport" + "_" + file.FromDate.ToString("yyyyMMdd") + "_" +
file.ToDate.ToString("yyyyMMdd") + "_" + file.RunTime.ToString("yyyyMMdd") + ".txt";
StreamWriter sw = new StreamWriter(Server.MapPath(serverPath + fileName), true);
foreach (var row in file.Rows)
{
sw.WriteLine(row.ToFileFormat());
}
sw.Close();
}
When the session ends, i.e. the user exits the browser I want all the files generated to be deleted. Is there any handler I can attach to do some clean up work? Or is there a better way to store the files during the session so that files do not have to be written to disk?
Note that I want to be able to access the file as a Href-link in the application.
Upvotes: 1
Views: 57
Reputation: 1969
Add your code in the Global.asax.cs preserved Session_End method:
protected void Session_End(object sender, EventArgs e)
{
...
}
Or you could also use application-wide event:
protected void Application_End(object sender, EventArgs e)
{
...
}
Upvotes: 0
Reputation: 11721
You don't have too much control over when the Session expires.
One solution would be to save the file content in the user session, and display it on a controller action. The .net will take care of clearing the session for you.
public ActionResult GetFile()
{
// file content from session
string fileContent = (string)HttpContext.Session["file"];
byte[] contentAsBytes = new System.Text.UTF8Encoding().GetBytes(fileContent);
return File(contentAsBytes, "text/plain");
}
Upvotes: 1