删除百万个文件的最快方法
Fastest way to delete million of files
我有一个字符串列表,它们是相对路径。我还有一个字符串,其中包含这些文件的根路径。现在我像这样删除它们:
foreach (var rawDocumentPath in documents.Select(x => x.RawDocumentPath))
{
if (string.IsNullOrEmpty(rawDocumentPath))
{
continue;
}
string fileName = Path.Combine(storagePath, rawDocumentPath);
File.Delete(fileName);
}
问题是我为每个文件都调用了 Path.Combine
,它已经够慢了。
我怎样才能加快这段代码?我无法删除整个文件夹,我无法更改当前目录(因为它会影响整个程序)...
我需要类似 class 的东西,它可以快速删除指定目录中的多个文件。
如果您的磁盘可以处理它,并行化应该会有很大帮助:
documents.AsParallel().ForAll(
document =>
{
if (!string.IsNullOrEmpty(document.RawDocumentPath))
{
string fileName = Path.Combine(storagePath, document.RawDocumentPath);
File.Delete(fileName);
}
});
我有一个字符串列表,它们是相对路径。我还有一个字符串,其中包含这些文件的根路径。现在我像这样删除它们:
foreach (var rawDocumentPath in documents.Select(x => x.RawDocumentPath))
{
if (string.IsNullOrEmpty(rawDocumentPath))
{
continue;
}
string fileName = Path.Combine(storagePath, rawDocumentPath);
File.Delete(fileName);
}
问题是我为每个文件都调用了 Path.Combine
,它已经够慢了。
我怎样才能加快这段代码?我无法删除整个文件夹,我无法更改当前目录(因为它会影响整个程序)...
我需要类似 class 的东西,它可以快速删除指定目录中的多个文件。
如果您的磁盘可以处理它,并行化应该会有很大帮助:
documents.AsParallel().ForAll(
document =>
{
if (!string.IsNullOrEmpty(document.RawDocumentPath))
{
string fileName = Path.Combine(storagePath, document.RawDocumentPath);
File.Delete(fileName);
}
});