6

I want to write some code that deletes all DIRECTORIES older than 7 days.

So:

  1. Check directory : D:\this
  2. If folder older than 7 days -> delete it from the system.
Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
1244
  • 97
  • 1
  • 3
  • 11

2 Answers2

18

You can lookup using the DirectoryInfo util

   DirectoryInfo d = new DirectoryInfo(dir);
   if (d.CreationTime    < DateTime.Now.AddDays(-7))
       d.Delete();
Erre Efe
  • 15,387
  • 10
  • 45
  • 77
  • last acces time are to be date created or? – 1244 Apr 26 '12 at 22:46
  • 7
    This will throw exception "the directory is not empty" in case if the directory is not empty. Use `Directory.Delete(dir, true)` if u want to delete directory and all of its content – Nizar Nov 23 '17 at 08:05
3

You can use DirectoryInfo

http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx

The voice of experience says to include sanity checks in your code that the directories you are deleting are in fact ones that you want to be deleting...

Eric J.
  • 147,927
  • 63
  • 340
  • 553