简体   繁体   中英

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.

My class struct is like below.

Class ImageDetails
{

public string Title;

public Boolean CanShow;

public String PathToFile;
}

I have an array of ImageDetails. The PathToFile contains full path

}

您可以使用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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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