Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete oldest Files in directory

Tags:

c#

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

Situation is as follows:

I would like to limit the amount of files in a directory to 5 files. Once that limit is reached I would like it to find the oldest file in the directory and delete it, so that the new file can be copied in.

I have been told to use filewatcher, however I have never used that function before.

like image 485
Shane Superfly MacNeill Avatar asked Nov 13 '13 09:11

Shane Superfly MacNeill


People also ask

How do I delete all old files?

Right-click your main hard drive (usually the C: drive) and select Properties. Click the Disk Cleanup button and you'll see a list of items that can be removed, including temporary files and more. For even more options, click Clean up system files. Tick the categories you want to remove, then click OK > Delete Files.


1 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, the argument in Skip(), and LastWriteTime to however you define 'oldest'.

The above gets all the files, orders them youngest first, skips the first 5, and deletes the rest.

like image 145
fejesjoco Avatar answered Sep 22 '22 22:09

fejesjoco