ASP.NET Schedule Delete Temporary Files

Question: I have an ASP.NET application that creates temporary PDF files (for user download). Now many users for many days can create many PDF files that take up a lot of disk space.

What is the best way to schedule file deletion older than 1 day / 8 hours? Preferably in the asp.net application itself ...

+4
source share
8 answers

For each temporary file that you want to create, record the file name in the session:

// create temporary file: string fileName = System.IO.Path.GetTempFileName(); Session[string.Concat("temporaryFile", Guid.NewGuid().ToString("d"))] = fileName; // TODO: write to file 

Then add the following cleanup code to global.asax:

 <%@ Application Language="C#" %> <script RunAt="server"> void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. // remove files that has been uploaded, but not actively 'saved' or 'canceled' by the user foreach (string key in Session.Keys) { if (key.StartsWith("temporaryFile", StringComparison.OrdinalIgnoreCase)) { try { string fileName = (string)Session[key]; Session[key] = string.Empty; if ((fileName.Length > 0) && (System.IO.File.Exists(fileName))) { System.IO.File.Delete(fileName); } } catch (Exception) { } } } } </script> 

UPDATE : I am now using a new (improved) method, different from the one described above. The new one includes HttpRuntime.Cache and checking that files are older than 8 hours. I will post it here if anyone is interested. Here is my new global.asax.cs :

 using System; using System.Web; using System.Text; using System.IO; using System.Xml; using System.Web.Caching; public partial class global : System.Web.HttpApplication { protected void Application_Start() { RemoveTemporaryFiles(); RemoveTemporaryFilesSchedule(); } public void RemoveTemporaryFiles() { string pathTemp = "d:\\uploads\\"; if ((pathTemp.Length > 0) && (Directory.Exists(pathTemp))) { foreach (string file in Directory.GetFiles(pathTemp)) { try { FileInfo fi = new FileInfo(file); if (fi.CreationTime < DateTime.Now.AddHours(-8)) { File.Delete(file); } } catch (Exception) { } } } } public void RemoveTemporaryFilesSchedule() { HttpRuntime.Cache.Insert("RemoveTemporaryFiles", string.Empty, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, delegate(string id, object o, CacheItemRemovedReason cirr) { if (id.Equals("RemoveTemporaryFiles", StringComparison.OrdinalIgnoreCase)) { RemoveTemporaryFiles(); RemoveTemporaryFilesSchedule(); } }); } } 
+4
source

Try using Path.GetTempPath() . It will provide you with the path to the temporary file folder of Windows. Then it will be up to the windows to clean :)

You can read more about the method here http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx

+1
source

The best way is to create a batch file that it is called by the Windows Task Scheduler at the interval you need.

OR

you can create a windows service with a class above

 public class CleanUpBot { public bool KeepAlive; private Thread _cleanUpThread; public void Run() { _cleanUpThread = new Thread(StartCleanUp); } private void StartCleanUp() { do { // HERE THE LOGIC FOR DELETE FILES _cleanUpThread.Join(TIME_IN_MILLISECOND); }while(KeepAlive) } } 

Note that you can also call this class in pageLoad, and this will not affect the process time, because the processing is in a different thread. Just remove do-while and Thread.Join ().

+1
source

How do you store files? If possible, you can simply go with a simple solution where all the files are stored in a folder named after the current date and time.
Then create a simple page or httphandler that will delete the old folders. You can call this page at intervals using a Windows schedule or another cron job.

0
source

Create a timer on Appication_Start and set a timer to call the method every 1 hour and clear files older than 8 hours or 1 day or whatever the duration you need.

0
source

I kind of agree with what was said in response from dirk.

The idea is that the temporary folder you drop the files to is a fixed known location, but I'm a little different ...

  • Each time a file is created, add the file name to the list in the session object (assuming there are not thousands, if there is, when this list falls into this cap, make the next bit)

  • when the session ends, the Session_End event should be raised in global.asax. Iterate all the files in the list and delete them.

0
source
  private const string TEMPDIRPATH = @"C:\\mytempdir\"; private const int DELETEAFTERHOURS = 8; private void cleanTempDir() { foreach (string filePath in Directory.GetFiles(TEMPDIRPATH)) { FileInfo fi = new FileInfo(filePath); if (!(fi.LastWriteTime.CompareTo(DateTime.Now.AddHours(DELETEAFTERHOURS * -1)) <= 0)) //created or modified more than x hours ago? if not, continue to the next file { continue; } try { File.Delete(filePath); } catch (Exception) { //something happened and the file probably isn't deleted. the next time give it another shot } } } 

The above code deletes the files in the temp directory that are created or modified more than 8 hours ago.

However, I would suggest using a different approach. As suggested by Fredrik Johansson, you can delete files created by the user at the end of the session. It is better to work with an additional directory based on the user session identifier in the temp directory. When the session ends, you simply delete the directory created for the user.

  private const string TEMPDIRPATH = @"C:\\mytempdir\"; string tempDirUserPath = Path.Combine(TEMPDIRPATH, HttpContext.Current.User.Identity.Name); private void removeTempDirUser(string path) { try { Directory.Delete(path); } catch (Exception) { //an exception occured while deleting the directory. } } 
0
source

Use the cache expiration notification to cause file deletion:

  private static void DeleteLater(string path) { HttpContext.Current.Cache.Add(path, path, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 8, 0, 0), CacheItemPriority.NotRemovable, UploadedFileCacheCallback); } private static void UploadedFileCacheCallback(string key, object value, CacheItemRemovedReason reason) { var path = (string) value; Debug.WriteLine(string.Format("Deleting upladed file '{0}'", path)); File.Delete(path); } 

ref: MSDN | How to notify an application when an item is removed from the cache

0
source

Source: https://habr.com/ru/post/1309753/


All Articles