Delete files older than x-amount of time


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Cleans the working folder of files older than 24 hours
  3. /// </summary>
  4. private void CleanWorkingFolder()
  5. {
  6. try
  7. {
  8. // Ensure the folder exists, if not create it
  9. if (Directory.Exists(this.WorkingLocation) == false)
  10. Directory.CreateDirectory(this.WorkingLocation);
  11.  
  12. // Ensure the folder exists, if not create it
  13. if (Directory.Exists(this.WorkingLocation) == false)
  14. return;
  15.  
  16. }
  17. catch (IOException ex)
  18. {
  19. EventLog log = new EventLog();
  20. log.Log = "Application";
  21. log.Source = "ImageHelper";
  22.  
  23. log.WriteEntry("Error trying to delete file: " + ex.ToString(), EventLogEntryType.Error);
  24. log.Close();
  25. }
  26. catch (Exception exGeneral)
  27. {
  28. EventLog log = new EventLog();
  29. log.Log = "Application";
  30. log.Source = "ImageHelper";
  31.  
  32. log.WriteEntry("Error trying to delete file: " + exGeneral.ToString(), EventLogEntryType.Error);
  33. log.Close();
  34. }
  35. foreach (var item in Directory.GetFiles(this.WorkingLocation))
  36. {
  37. try
  38. {
  39. FileInfo info = new FileInfo(item);
  40. // Delete the file only if it's at least a day old
  41. if (info.CreationTime < DateTime.Now.AddDays(-1))
  42. File.Delete(item);
  43. }
  44. catch (IOException ex)
  45. {
  46. EventLog log = new EventLog();
  47. log.Log = "Application";
  48. log.Source = "ImageHelper";
  49.  
  50. log.WriteEntry("Error trying to delete file: " + ex.ToString(), EventLogEntryType.Error);
  51. log.Close();
  52. }
  53. catch (Exception exGeneral)
  54. {
  55. EventLog log = new EventLog();
  56. log.Log = "Application";
  57. log.Source = "ImageHelper";
  58.  
  59. log.WriteEntry("Error trying to delete file: " + exGeneral.ToString(), EventLogEntryType.Error);
  60. log.Close();
  61. }
  62. }
  63.  
  64. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.