welcome the essence of the question in the title. There is an application that scans a folder each time you log in for extra files. extras are those that are not defined in the list. actually:

private void DeleteFILES(DAL dal) { List<string> Equals = new List<string>(); for (int i = 0; i < dal.getMNamesfromBD().Count; i++) { Equals.Add(dal.getMNamesfromBD()[i].ToString()); } try { string CompletePatchToEXE = Directory.GetCurrentDirectory(); DirectoryInfo dir = new DirectoryInfo(CompletePatchToEXE + @"\\materials\\"); foreach (FileInfo file in dir.GetFiles()) { for (int i=0; i<dal.getMNamesfromBD().Count; i++) { if (file.Name != Equals[i]+ ".jpg") { file.Delete(); } } } MessageBox.Show("Файлы поставленные в очереди были успешно удалены!", "Редактирование"); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source); } } 

however, instead of deleting files that are not registered in Equals, the code deletes all files altogether. I can not find a mistake, tell me where to fix it? thank!

  • So if (file.Name != Equals[i]+ ".jpg") in a loop where you can’t write an action at the same time. this is the line with the error - nick_n_a
  • 2
    Suppose the first element matched - not deleted, but then the second element of the array does not exactly match - and the action will be deleted. - nick_n_a
  • pancake! completely missed such a moment, and after all the truth. - Sergey
  • You can 1) use List and make List.IndexOf() < 0 2) use bool moisture, instead of deleting in a loop do keepFile=true; and after the cycle if (!keepFile) delete - nick_n_a
  • one
    Having found -1 you will know that the element is not in the list, finding the number >=0 you will know that the element is in the list. And you can remove the verification cycle. (But then there will be a cycle that will fill the list) - nick_n_a

1 answer 1

The code can be greatly simplified using LINQ.

Also master the Path.Combine method for working with file system paths.

 var materialsDirectory = Path.Combine(Application.StartupPath, "materials"); List<string> Equals = // заполняем список из БД var distinct = Directory.GetFiles(materialsDirectory) .Except(Equals.Select(s => Path.Combine(materialsDirectory, s, ".jpg"))); foreach (var fileName in distinct) new FileInfo(fileName).Delete(); 

If I understand correctly, the list contains only file names without a full path and no extension.

PS Judging by your other questions, the materials folder is used in many places of the code. Therefore, add a form field, where you enter the desired path once at the start of the application, and then just use it.