简体   繁体   English

搜索和删除目录中文件的最快方法

[英]fastest way to search and delete files inside a directory

I've got a array of class in which one member is the full path to a file. 我有一个类数组,其中一个成员是文件的完整路径。 I need to delete all those files from the directory which is not included in the array. 我需要从目录中删除所有那些未包含在数组中的文件。 As Usual, I am using the convential compare and delete method. 通常,我使用传统的比较和删除方法。 I need to know if there any fast way to accomplish this. 我需要知道是否有任何快速的方法来实现这一目标。 I heard it can be done using Linq, but i dont have knowledge on linq. 我听说可以使用Linq完成,但我对linq没有任何了解。

My class struct is like below. 我的类结构如下所示。

Class ImageDetails
{

public string Title;

public Boolean CanShow;

public String PathToFile;
}

I have an array of ImageDetails. 我有一个ImageDetails数组。 The PathToFile contains full path PathToFile包含完整路径

} }

您可以使用Except()来处理:

var filesToDelete = Directory.GetFiles(Path.GetDirectoryName(yourClass.FilePath)).Except(yourClass.TheArray);

Why do you need to compare? 你为什么需要比较? If you have the full file name, then 如果您有完整的文件名,那么

File.Delete(fileName);

is all you need. 是你所需要的全部。 The file IO is likely to be the slowest part of this, so I don't think Linq will make much difference to the performance. 文件IO可能是最慢的部分,所以我认为Linq不会对性能产生太大影响。

If the file may not exist, then check for that first: 如果该文件可能不存在,请先检查该文件:

if (File.Exists(fileName))
{
    File.Delete(fileName);
}

Edit: I see you mean that you want to delete the file if it is not in the array. 编辑:我看到你的意思是你要删除文件,如果它不在数组中。 I read your question to mean that the directory is not included in the array. 我读了你的问题意味着该目录未包含在数组中。

Still, the actual file deletion is likely to be the slowest part of this. 尽管如此,实际的文件删除可能是最慢的部分。

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

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