logeeks
logeeks

Reputation: 4979

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

}

Upvotes: 1

Views: 763

Answers (2)

Polyfun
Polyfun

Reputation: 9639

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.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

You can use Except() to handle this:

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

Upvotes: 4

Related Questions