我正在使用以下代码删除超过10天的文件。有没有更简单/更聪明的方法呢?
string source_path = ConfigurationManager.AppSettings["source_path"];
string filename= ConfigurationManager.AppSettings["filename"];
var fileQuery= from file in Directory.GetFiles(source_path,filename,SearchOption.TopDirectoryOnly)
where File.GetCreationTime(file)<System.DateTime.Now.AddDays(-10)
select file;
foreach(var f in fileQuery)
{
File.Delete(f);
}
答案 0 :(得分:6)
我有两件事要改变:
DateTime
一次,而非重复评估DateTime.Now
where
子句时,我不会使用查询表达式:所以我将查询部分重写为:
var cutoff = DateTime.Now.AddDays(-10);
var query = Directory.GetFiles(sourcePath, filename, SearchOption.TopDirectoryOnly)
.Where(f => File.GetCreationTime(f) < cutoff);
另一种选择是使用DirectoryInfo
和FileInfo
:
var cutoff = DateTime.Now.AddDays(-10);
var path = new DirectoryInfo(sourcePath);
var query = path.GetFiles(filename, SearchOption.TopDirectoryOnly)
.Where(fi => fi.CreationTime < cutoff);
(在.NET 4中,您可能还想使用EnumerateFiles
。)
答案 1 :(得分:-1)
可以执行LINQ“one-liner”来执行此过程:
Directory.GetFiles(source_path,filename,SearchOption.TopDirectoryOnly)
.Where(f => File.GetCreationTime(file) < System.DateTime.Now.AddDays(-10))
.All(f => {File.Delete(f); return true;);
不要忘记将代码包装在try catch中。