0

Possible Duplicate:
C# 4.0 unlock image after creating BitmapImage

I have this code to create an Image file in WPF.

var newimage = new System.Windows.Controls.Image
{
    Stretch = Stretch.Fill,
    StretchDirection = StretchDirection.Both,
    Width = Width,
    Height = Height
};

var logo2 = new BitmapImage();
logo2.BeginInit();
logo2.UriSource = uri;
logo2.EndInit();
newimage.Source = logo2;

After this some process have to delete ol file and create a new one but I'm facing an error

"Cannot delete file because it is being used by another process"

What should I do to fix this issue?

Thank you!


P.S.

I delete the file using this:

try
{
    if (File.Exists(fileName))
    {
        File.Delete(fileName);
        Debug.WriteLine("FILE MANAGER: File " + fileName + " has been deleted.");
    }
    return true;
}
Community
  • 1
  • 1
NoWar
  • 36,338
  • 80
  • 323
  • 498

1 Answers1

1

You would need to use:

var logo2 = new BitmapImage();
logo2.BeginInit();
logo2.CacheOption = BitmapCacheOption.OnLoad;
logo2.UriSource = uri;
logo2.EndInit();
CodeNaked
  • 40,753
  • 6
  • 122
  • 148
  • Can I just read this file into memory and dont lock the disk image file? – NoWar Oct 26 '12 at 17:38
  • 1
    @Peretz - Possibly, but what I have above is generally better as you would have to figure out who disposes of the MemoryStream. See http://stackoverflow.com/questions/6430299/bitmapimage-in-wpf-does-lock-file/6430416#6430416 – CodeNaked Oct 26 '12 at 17:48