问题
My website creates a bunch of png files while converting documents from pdf. I have all those files uniquely identified and I want them to be removed at session end. My idea was to create a List, store it in Session and delete each file by path stored in my List<>.
In Global.asax I added:
void Session_End(object sender, EventArgs e)
{
if (Session["cleanUpCollection"] != null)
{
List<String> deletePaths = ((List<string>)(Session["cleanUpCollection"]));
foreach(String s in deletePaths)
{
try
{
System.IO.File.Delete(s);
}
catch { }
}
}
}
In web.config I added this:
<sessionState mode="InProc" cookieless="false" timeout="20" />
but files still sit in temporary location. I have yet to test where this fails but is there a better, common practice of deleting temporary files at session end? BTW, I verified and cleanUpCollection stores local server's paths so there is no error in file path.
回答1:
A more robust approach to this would be to have a scheduled job running on your server (outside of your site) that periodically cleans up this folder, removing files older than a certain age. Relying on session timeout for this is not ideal.
I would also note that you have given us no indication of what error is occuring or why the files are not deleted. For more help on that, please provide some info.
回答2:
With the timeout set to 20 that means it will take 20 minutes before the session is abandoned and your code is executed. Also, Session_End event doesn't fire unless the session idles out and doesn't fire when someone navigates to another page or closes the browser so this code may not always clean up the directory.
Rather than waiting for the user session to end before deleting, I suggest deleting the files once the PDF has been created.
来源:https://stackoverflow.com/questions/24084588/delete-temp-files-on-session-end-in-asp-net