Файл занят другим процессом - C# (182685)

Узнай цену своей работы

Формулировка задачи:

the process cannot access the file... because it is being used by another process Пытаюсь удалить файлы, которые до этого добавлял в bitmapCollection и сравнивал на подобие
Листинг программы
  1. // ... какой то код
  2. while(true)
  3. {
  4. switch(selection){
  5. // пару case'ов
  6. //....
  7. case "compare":
  8. string[] filesCollection = Directory.GetFiles(mainPath, "*.png"); // path of every single photo
  9. if (Directory.Exists(mainPath) && filesCollection.Length >= 2)
  10. {
  11. Array.Sort(filesCollection);
  12. Bitmap[] bitmapCollection = new Bitmap[filesCollection.Length];
  13. int i = 0;
  14. foreach (string item in filesCollection)
  15. {
  16. bitmapCollection[i] = new Bitmap(item.ToString());
  17. i++;
  18. Console.WriteLine("{0} из {1}", i, filesCollection.Length);
  19. }
  20. // узнаем 1 процент от общего кол-ва элементов
  21. double percent = (double)bitmapCollection.Length / (double)100;
  22. // 100 %
  23. List<double> percentsList = new List<double>();
  24. for (int s = 1; s < 101; s++)
  25. {
  26. percentsList.Add(percent * s);
  27. }
  28. //
  29. Console.WriteLine("Коллекция фотографий успешно собрана.");
  30. Console.WriteLine("Начинается проверка фотографий....");
  31. // int value = 1;
  32. bool bFlag = false;
  33. List<TrashPaths> repeatPhotosList = new List<TrashPaths>();
  34. List<int> arrayX = new List<int>(); // Чтобы J не повторял уже пройденные X
  35. for (int x = 0; x < bitmapCollection.Length; x++)
  36. {
  37. // Console.WriteLine("Цикл {0} из {1} итераций", x, bitmapCollection.Length - 1);
  38. for (int j = 0; j < bitmapCollection.Length; j++)
  39. {
  40. bool isNext = false;
  41. if (arrayX.Count >= 1)
  42. {
  43. foreach (var arrayItem in arrayX)
  44. {
  45. if (j == arrayItem)
  46. {
  47. isNext = true;
  48. break;
  49. }
  50. }
  51. }
  52. if (isNext == true)
  53. {
  54. continue;
  55. }
  56. bFlag = PhotoComparing.ImageCompareArray(bitmapCollection[x], bitmapCollection[j]);
  57. if (bFlag == true && x != j)
  58. {
  59. ChangeColor.greenForeground();
  60. string TheSameX = filesCollection[x];
  61. string TheSameJ = filesCollection[j];
  62. TheSameX = TheSameX.Replace(mainPath + @"", "");
  63. TheSameJ = TheSameJ.Replace(mainPath + @"", "");
  64. repeatPhotosList.Add(new TrashPaths() { image = bitmapCollection[x], path = TheSameX });
  65. Console.WriteLine("Найден подобный. " + TheSameX + " похож с " + TheSameJ);
  66. ChangeColor.ResetColor();
  67. arrayX.Add(x);
  68. filesToDelete.Add(filesCollection[x]);
  69. }
  70. bFlag = false;
  71. }
  72. Console.WriteLine("{0} из {1} проверок", x, bitmapCollection.Length);
  73. /*
  74. //if (value < 100)
  75. // {
  76. if (((double)x >= (percentsList[value] - 2)) && ((double)x <= percentsList[value]))
  77. {
  78. ChangeColor.redForeground();
  79. Console.WriteLine("{0} из {1} проверок", x,j);
  80. value++;
  81. ChangeColor.ResetColor();
  82. }
  83. // }*/
  84.  
  85. }
  86. Console.WriteLine();
  87. ChangeColor.redForeground();
  88. Console.WriteLine("100% Завершено");
  89. ChangeColor.greenForeground();
  90. Console.WriteLine("Копирование дубликатов...");
  91. ChangeColor.ResetColor();
  92. int kolvo = 0;
  93. if (!Directory.Exists(mainPath + @"\Trash"))
  94. {
  95. DirectoryInfo dir2 = new DirectoryInfo(mainPath + @"\Trash");
  96. dir2.Create();
  97. }
  98. foreach (var image in repeatPhotosList)
  99. {
  100. image.image.Save(string.Format(mainPath + @"\Trash\{0}.png", image.path), System.Drawing.Imaging.ImageFormat.Png);
  101. kolvo++;
  102. }
  103. canDelete = true;
  104. Console.WriteLine("Нажмите Enter для продолжения...");
  105. Console.ReadLine();
  106. }
  107. else
  108. {
  109. ChangeColor.redForeground();
  110. Console.WriteLine("{0} не существует. Измените путь на подобающий. Пример: D:\\photos",mainPath);
  111. Console.WriteLine("Или в {0} меньше 2 изображений.\n Пожалуйста, выполните сперва команду download", mainPath);
  112. ChangeColor.ResetColor();
  113. }
  114. break;
  115. }
  116. if (canDelete == true)
  117. {
  118. ChangeColor.redForeground();
  119. Console.WriteLine("Начинается процесс удаления лишних изображений в главной папке...");
  120. foreach (var deleteFile in filesToDelete)
  121. {
  122. File.Delete(deleteFile);
  123. Console.WriteLine("{0} удален", deleteFile.ToString());
  124. }
  125. ChangeColor.ResetColor();
  126. canDelete = false;
  127. }
  128. }

Решение задачи: «Файл занят другим процессом»

textual
Листинг программы
  1. new Bitmap(item.ToString());

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 4.2 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы