Deleting temporary files from a folder
-
My web application needs to write files in a temp folder. The files have to be deleted later, otherwise the disk on the server will be filled up. So I wrote the following code to be executed in a background thread periodically:
// delete files more than 1 day old DateTime now = DateTime.Now; string[] pFiles = Directory.GetFiles(sTempFolder,"*.*"); for(int i=0;i<pFiles.Length;i++) { try { if(File.GetCreationTime(pFiles[i]).AddDays(1)<now) { File.Delete(pFiles[i]); } } catch(Exception oBug) { /* error handling */ } }
Then I copied some old files (much older than 1 day) into the temp folder and try to test the code. It does not work. It turns out, it would have worked if I waited for a day after copying the files. The "creation time" for the old files I copied was set to the current time, the explorer shows the "last modification time". If I change GetCreationTime to GetLastWriteTime, then it will work right away. -
My web application needs to write files in a temp folder. The files have to be deleted later, otherwise the disk on the server will be filled up. So I wrote the following code to be executed in a background thread periodically:
// delete files more than 1 day old DateTime now = DateTime.Now; string[] pFiles = Directory.GetFiles(sTempFolder,"*.*"); for(int i=0;i<pFiles.Length;i++) { try { if(File.GetCreationTime(pFiles[i]).AddDays(1)<now) { File.Delete(pFiles[i]); } } catch(Exception oBug) { /* error handling */ } }
Then I copied some old files (much older than 1 day) into the temp folder and try to test the code. It does not work. It turns out, it would have worked if I waited for a day after copying the files. The "creation time" for the old files I copied was set to the current time, the explorer shows the "last modification time". If I change GetCreationTime to GetLastWriteTime, then it will work right away.Hi! Leaving temp files on the disk for longer than absolutely neccessary is a potential security risk. Shouldn't you remove the temp files as soon as your app doesn't need them any more instead of deleting files of a certain age?
Regards, mav -- Black holes are the places where God divided by 0...