Wednesday, 7 July 2010

DELETE FILES OLDER THAN X-AMOUNT OF TIME

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

No comments:

Post a Comment