0

I use this function to load a photo:

private void Load_Photo()
{
   BitmapImage bi1 = new BitmapImage();
   bi1.BeginInit();
   bi1.UriSource = new Uri(photolocation, UriKind.Absolute);
   bi1.EndInit();

   if (bi1 != null)
   {
     Image_Data = bi1;
   }
}

Then I want to save over the same photo that gives me an error saying: System.IO.IOException 'The proces cannot access the file 'photolocation' because it is being used by another process.

private void Save_Photo_To_JPG()
{
   var encoder = new JpegBitmapEncoder();

   encoder.Frames.Add(BitmapFrame.Create(Image_Data));

   using (var filestream = new FileStream(photolocation, FileMode.Create))

   encoder.Save(filestream);
}

How can I solve this?

aeternus
  • 34
  • 4
  • Do you want to overwrite existing file or create new file/folder? You are using Create which will overwrite existing file, but existing file is still opened. – jdweng Jun 14 '20 at 15:47
  • 2
    Watch your indentation. If you're not going to indent `encoder.Save()`, you should just assume braces are required for your `using` statement. – Robert Harvey Jun 14 '20 at 18:22

1 Answers1

0

This worked for me:

using (FileStream fs = new FileStream(path, FileMode.Open))
{
    bitmap.BeginInit();
    bitmap.StreamSource = fs;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();
}
aeternus
  • 34
  • 4