简体   繁体   English

删除目录中最旧的文件

[英]Delete oldest Files in directory

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. 我想将目录中的文件数量限制为5个文件。 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. 我被告知要使用filewatcher,但我之前从未使用过该函数。

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'. 更改目录名称,Skip()和LastWriteTime中的参数,但是您定义“最旧”。

The above gets all the files, orders them youngest first, skips the first 5, and deletes the rest. 以上获取所有文件,首先命令最小,跳过前5个,然后删除其余文件。

You can use DirectoryInfo.EnumerateFiles to get the files in the folder, order them by CreationTime with Enumerable.OrderByDescending , use Enumerable.Take(5) to get the 5 last created files. 您可以使用DirectoryInfo.EnumerateFiles来获取文件夹中的文件,通过CreationTime使用Enumerable.OrderByDescending它们进行排序,使用Enumerable.Take(5)获取最后创建的5个文件。 If there are more the List.ForEach will delete them. 如果有更多的List.ForEach将删除它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM