Delete temp files on Session end in ASP.NET

巧了我就是萌 提交于 2021-01-28 07:06:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!