0

I want to search for the characters in Name file of the Directory. If the content is different from the results found, delete the file. I've tried the code below:

private void btnStart_Click(object sender, EventArgs e) { FileWithFilter(Parth, "Abc123"); } private void FileWithFilter(string folderName, string filesToExclude) { DateTime dateTime = DateTime.Now; DirectoryInfo dir = new DirectoryInfo(folderName); foreach (FileInfo fi in dir.GetFiles()) { if (!fi.Name.Contains(filesToExclude)) { fi.delete(); } } } 

It works, but if the file in Directory is more than 10 or 11(file), code can't run correctly! please tell me any better way or other solution.

7
  • 1
    Instead of deleting from within the directory enumeration you might try storing the names of files to be deleted in a list and delete them after. Commented Oct 14, 2021 at 12:24
  • 3
    Define "Can't run correctly". Do you get an error? If so, what is it? If not, in what way is the program not meeting your expectations? Commented Oct 14, 2021 at 12:24
  • Ignore the case with !fi.Name.Contains(filesToExclude, StringComparison.OrdinalIgnoreCase). Commented Oct 14, 2021 at 12:30
  • It worked but in correct. when I try more than 10 files. The program delete wrong file with contains the correct . 10 files with name : 1.ACB.tar , 2.ABC.tar, 3ABC.tar ... 10.ABC.tar Commented Oct 14, 2021 at 13:23
  • 1
    "1.ACB.tar" does not contain "Abc123", so it will be deleted. Commented Oct 14, 2021 at 15:47

1 Answer 1

2

I would propose to save all files which should be deleted in a list and then delete them afterwards. It is not recommendd to manipulate the list you are iterating over.

 private void FileWithFilter(string folderName, string filesToExclude) { List<string> filesToBeDeleted = Directory.GetFiles(folderName).Where(m => !m.Contains(filesToExclude)).ToList(); filesToBeDeleted.ForEach(m => File.Delete(m)); } 
Sign up to request clarification or add additional context in comments.

3 Comments

It worked but in correct. when I try more than 10 files. The program delete wrong file with contains the correct . 10 files with name : 1.ACB.tar , 2.ABC.tar, 3ABC.tar ... 10.ABC.tar
This should not be necessary, as GetFiles returns an array.
returns an array of strings, so there is also an implicit cast to FileInfo which is unecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.