views:

299

answers:

1

I have an image control with a source image located in my c drive. I get a message that the image is being used by another process whenever I try to delete the original image to change it with another one dynamically. How do I release the image from the image control to be able to delete it.

I tried this variants:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);

And:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)

But it's not work...

+1  A: 

Try setting the bitmap image through the stream source property. That way the app won't put a lock on the file since you loaded it through a stream.

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.streamsource(VS.85).aspx

Kevin
2Kevin: Interesting way, but in this situation I need fs.Close() before File.Delete. It's not very convenient. Is there some other option?
antongladchenko
The other option I saw was to copy the image to a temp directory and open the temp file.
Kevin
I saw other posts where it looks like the file just locks even after the control should release the image for some reason without explanation.
Kevin
Clearly. Thanks for your help!
antongladchenko