Delete old files in a directory

I have a question about deleting the oldest file in a directory.

The situation is as follows:

I would like to limit the number of files in a directory to 5 files. Once this restriction is reached, I would like it to find the oldest file in the directory and delete it so that you can copy the new file.

I was told to use filewatcher, however, I had never used this function before.

+4
source share
2 answers
using System.IO; using System.Linq;

foreach (var fi in new DirectoryInfo(@"x:\whatever").GetFiles().OrderByDescending(x => x.LastWriteTime).Skip(5))
    fi.Delete();

Change the directory name, argument in Skip (), and LastWriteTime to define "oldest."

All the above files, first order them younger, skip the first 5 and delete the rest.

+23
source

DirectoryInfo.EnumerateFiles, , CreationTime Enumerable.OrderByDescending, Enumerable.Take(5), 5 . , List.ForEach .

var files = new DirectoryInfo("path").EnumerateFiles()
     .OrderByDescending(f => f.CreationTime)
     .Skip(5)
     .ToList();
files.ForEach(f => f.Delete());
+3

All Articles