0

I have a WPF application which successively displays images from a ObservableCollection (includes strings with the image paths)

<Image Source="{Binding ListOfUnsortedImages[0], UpdateSourceTrigger=PropertyChanged}" />

This is the collection including the image paths:

private ObservableCollection<String> _listOfUnsortedImages = new ObservableCollection<String>();

The application displays the image and after clicking a button, the application copies the image, removes it from the collections and shows the next image.

This is the reduced logic of the button:

Image img;
var currentImage = ListOfUnsortedImages[0];

using (Stream stream = File.OpenRead(currentImage))
{
    img = System.Drawing.Image.FromStream(stream);

    // Do something with the image
    img.Dispose();
    stream.Dispose();
}

ListOfUnsortedImages.RemoveAt(0);
File.Delete(currentImage);

The last line fires the IOException:

The process cannot access the file 'filename' because it is being used by another process

I've tried to solve the issue by using Dispose() and/or using{} but without success.

Sebastian
  • 377
  • 1
  • 2
  • 17
  • If you skip using block, can you delete file? You will know then if problem is inside this block – daniell89 Mar 22 '17 at 08:46
  • How do you put your source under your path? May be it will be not released by copy, so you can read, but can not delete? Shure, that no processes use the source, but only your application? – Rekshino Mar 22 '17 at 08:48
  • If you don't want to change your code - you can create converter that will create `BitmapImage` from string with BitmapCacheOption.OnLoad. – Evk Mar 22 '17 at 09:28

1 Answers1

0

Problem might not be in your code since the lock is caused by another process. Have you tried deleting the file using a file manager to see if it's still locked when your application isn't running? Alternatively try ditching the FileStream and use System.Drawing.Image.FromFile() instead since you have the filename anyway in your ObservableCollection, see MSDN

Neil Humby
  • 253
  • 4
  • 15
  • Yes, I've tried to delete the image by the file manager but the same problem here. I also tried not using FileStream and only use your suggestion, still same problem. – Sebastian Mar 22 '17 at 09:02
  • Maybe there you'll find method to identify which proces is blocking your file:http://stackoverflow.com/q/317071/5358389 – daniell89 Mar 22 '17 at 09:05
  • I've also Clear(); the collection before deleting the file, but it also not works. @daniell89 If I try to delete the file by a file manager it shows me that the blocking process is vshost32.exe – Sebastian Mar 22 '17 at 09:12
  • Try to run app without debugger (CTRL + F5) – daniell89 Mar 22 '17 at 09:16
  • Now, the app crashes (my test code is not in try catch, so the same problem here) – Sebastian Mar 22 '17 at 09:22