有条件删除文件的更好方法是什么 [英] What is better way to delete file with condition
问题描述
我想在c#上构建一个win服务(没有UI),它要做的就是:在目录列表上运行并删除X kb以上的文件. 我想要更好的性能,
I want to build a win service(no UI) on c# that all what it done is: run on list of directories and delete files that over then X kb. I want the better performance,
什么是更好的方法? 没有用于删除文件的纯异步功能,所以如果我想使用异步等待 我可以像这样包装此功能:
what is the better way to do this? there is no pure async function for delete file so if i want to use async await I can wrap this function like:
public static class FileExtensions {
public static Task DeleteAsync(this FileInfo fi) {
return Task.Factory.StartNew(() => fi.Delete() );
}
}
并调用此函数,如:
FileInfo fi = new FileInfo(fileName);
await fi.DeleteAsync();
我认为跑步方式
foreach file on ListOfDirectories
{
if(file.Length>1000)
await file.DeleteAsync
}
,但是在此选项上,文件将一一删除(并且每个DeleteAsync将在threadPool中的线程上使用). 所以我不能从异步中赚钱,我可以1比1做到这一点.
but on this option the files will delete 1 by 1 (and every DeleteAsync will use on thread from the threadPool). so i not earn from the async, i can do it 1 by 1.
也许我想收集列表中的X个文件,然后将它们删除为AsParallel
maybe i think to collect X files on list and then delete them AsParallel
请帮助我找到更好的方法
please help me to find the better way
推荐答案
这可能会对您有所帮助.
this is may be can help you.
public static class FileExtensions
{
public static Task<int> DeleteAsync(this IEnumerable<FileInfo> files)
{
var count = files.Count();
Parallel.ForEach(files, (f) =>
{
f.Delete();
});
return Task.FromResult(count);
}
public static async Task<int> DeleteAsync(this DirectoryInfo directory, Func<FileInfo, bool> predicate)
{
return await directory.EnumerateFiles().Where(predicate).DeleteAsync();
}
public static async Task<int> DeleteAsync(this IEnumerable<FileInfo> files, Func<FileInfo, bool> predicate)
{
return await files.Where(predicate).DeleteAsync();
}
}
var _byte = 1;
var _kb = _byte * 1000;
var _mb = _kb * 1000;
var _gb = _mb * 1000;
DirectoryInfo d = new DirectoryInfo(@"C:\testDirectory");
var deletedFileCount = await d.DeleteAsync(f => f.Length > _mb * 1);
Debug.WriteLine("{0} Files larger than 1 megabyte deleted", deletedFileCount);
// => 7 Files larger than 1 megabyte deleted
deletedFileCount = await d.GetFiles("*.*",SearchOption.AllDirectories)
.Where(f => f.Length > _kb * 10).DeleteAsync();
Debug.WriteLine("{0} Files larger than 10 kilobytes deleted", deletedFileCount);
// => 11 Files larger than 10 kilobytes deleted
这篇关于有条件删除文件的更好方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!