I am developing a commenting system with asp.net. A user can attach an image with "Attach" button and post the comment with "Post" button. Uploading the image starts when the user attaches it. An ASHX handler saves the uploaded file to "temp" folder. If the user clicks "Post" button, I move the image into a safe place. If he doesn't click "Post", closes the browser and goes away, the file remains in the "temp" folder. How can I delete a file from this "temp" folder one hour later after it is uploaded?
Details: I thought using System.Timers.Timer in the ashx file used for uploading
System.Timers.Timer timer = new System.Timers.Timer(300);
string fileName;
public void Cleaner()
{
System.Timers.Timer timer = new System.Timers.Timer(300); //3 second
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs a)
{
timer.Stop();
timer.Close();
string path = "temp";
string mapPath = HttpContext.Current.Server.MapPath("../" + path);
FileInfo TheFile = new FileInfo(mapPath + "\\" + fileName);
if (TheFile.Exists) File.Delete(mapPath + "\\" + fileName);
}
public void ProcessRequest(HttpContext context)
{
//Saving uploaded file
Cleaner();
}
but I feel that I am not doing right.
Timer ticks after 3 seconds but HttpContext.Current in the timer_Elapsed() function returns null. Besides, file name also returns null after timer ticks. I couldn't find a way to pass file name as a parameter when binding an event. Simply, it is problematic. I am looking for a more elegant way to delete the uploaded file after one hour.
I would avoid timers as you will create one timer per file which will not scale very well at all.
How about this, run a clean up process on another thread in the web app started on app start that will delete temp files each time a session expires. That way you need no timers as the process will be prompted each time a session expires. You will need a class to store a reference (by unique name I guess) to the file which are still live (by that I mean the session to which they belong is still live) which the clean process can check.
LMK if you want some code pointers.