tags:

views:

364

answers:

8

I would like to know (using c#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible.

Just to be clear - I am looking for files that are older than 90 days, in other words files created less than 90 days ago should be kept, all others deleted.

+2  A: 

The GetLastAccessTime property on the System.IO.File class should help.

Keith Bloom
+1  A: 

Basically you can use Directory.Getfiles(Path) to get a list of all the files. After that you loop through the list and call GetLastAccessTim() as Keith suggested.

Ian Jacobs
A: 

hi you just need FileInfo -> CreationTime

and than just calculate the time difference.

in the app.config you can save the TimeSpan value of how old the file must be to be deleted

also check out the DateTime Subtract method.

good luck

nWorx
+2  A: 

Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):

    DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);

    // Get info of each file into the directory
    foreach (FileInfo fi in source.GetFiles())
    {
        var creationTime = fi.CreationTime;

        if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
        {
            fi.Delete();
        }
    }
Pierre-Luc Champigny
No need for `ToList()`, `DirectoryInfo.GetFiles()` returns a `FileInfo[]`.
Dynami Le Savard
Yeah thank you! So no need for the ToList()
Pierre-Luc Champigny
A: 

Alternatively, you can use the File.GetCreationTime Method if you need to delete files based on creation dates.

jinsungy
+8  A: 

Something like this outta do it.

using System.IO; 

string[] files = Directory.GetFiles(dirName);

foreach (string file in files)
{
   FileInfo fi = new FileInfo(file);
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
      fi.Delete();
}
Steve Danner
Thanks, I noticed you're using lastAccessTime, is this the creation time?
JL
no, as propertyNames says: `LastAccessTime` - you should go for property `CreationTime` if you'd like to!
Andreas Niedermair
Yeah, which property you use is entirely up to you. You could also use LastWriteTime if you wanted.
Steve Danner
Sorry to ask, but are you 100% sure about the comparison operator being less than? does this mean that the first date should be less than the 2nd date?
JL
No need to apologize, that is how you learn! Yes, I'm positive. It means the last access time on the file is less than the date 3 months ago from this moment.
Steve Danner
Ok thanks Steve, you got here first with a great answer, thanks again!
JL
Use LINQ dammit!
Filip Ekberg
A: 

The code could look like this:

bool allFilesDeleted = 
 (from f in Directory.GetFiles(dirName)
 let info = new FileInfo(f)
 where info.LastAccessTime < 3.Months().Ago
 select info.AsSideEffect(i=>i.Delete())
 .All(success=>success);

Update: LOL! Didn't expect such a negative reception, but people don't read anymore...I clearly stated that the code could look like this. What is obviously missing in the .NET Framework is an Extension method "Months()" applicable to int that will return a date 3 months in the past. How this can work is shown here: http://realfiction.net/Content/Entry/77

What is also obviously missing is an extension method to perform a side-effect in LINQ which can look something like this:

public static bool AsSideEffect<T>(this T target, Action<T> action)
{
  try
  {
    action(target);
    return true;
  }
  catch (Exception x)
  {
    return false;
  }
}

which would allow Binding a void method into the iteration of a LINQ expression. OMG guys, it's Monday, give it a rest!

flq
I would have upvoted 'cause this looks great, but doesn't compile. `.Months`, `.Ago` and `.AsSideEffects` not recognized. Where are they from?
Sam
+4  A: 

For those that like to over-use LINQ.

(from f in new DirectoryInfo("C:/Temp").GetFiles()
 where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
 select f
).ToList()
    .ForEach(f => f.Delete());
Sam
var filesToDelete = new DirectoryInfo(@"C:\Temp").GetFiles().Where(x=>x.LastAccessTime < DateTime.Now.AddMonths(-3)); //variation
RandomNoob
Woho! Someone else than me thinks over-using LINQ is awesome! ;)
Filip Ekberg
What does the `.ToList()` call add other than a second loop through the matched files?
Joel Mueller
@Joel Mueller. `List<T>` defines a `ForEach` method which can be used to apply an `Action<T>` to all elements. Unfortunately there is no such extension method for `IEnumerable<T>`.
Sam
@Sam - Good point. I wrote my own `ForEach` extension method for `IEnumerable<T>` so long ago, I sometimes forget it isn't built in.
Joel Mueller