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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With