You need to release the 1.jpg file for writing after BitmapImage started working with another file.

Here is the code

 using System; using System.Drawing; //в ссылке System.Drawing using System.Windows.Media.Imaging;//в ссылке PresentationCore namespace Test { class Program { static void Main(string[] args) { BitmapImage img; img = new BitmapImage(new Uri(@"D:\img\1.jpg")); //Несмотря на переход к 2.jpg, файл 1.jpg остается занят img = new BitmapImage(new Uri(@"D:\img\2.jpg")); Image i = Image.FromFile(@"D:\img\3.jpg"); Console.WriteLine(@"Try write in D:\img\1.jpg"); Console.ReadKey(); i.Save(@"D:\img\1.jpg"); } } } 

    2 answers 2

    The problem is in particular behavior. A slightly different solution:

     public static ImageSource BitmapFromUri(Uri source) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = source; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); return bitmap; } 

    After creating the file will be immediately closed.

    Related Links:

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/5b2270cb-f182-4f5f-a6c6-c78dfe4e3230/how-to-dispose-a-systemwindowsmediaimagesourceforum=wpf https://stackoverflow.com / questions / 10319447 / release-handle-on-file-imagesource-from-bitmapimage

    • It is clear why I could not find the answer myself. Thank. - Ilya
    • It is worth adding bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache; . Then it will be possible to re-upload the file with the same name, but already changed contents. - Ilya

    Try to initialize the drawing otherwise:

     var stream = File.OpenRead(Directory.GetCurrentDirectory() + @"\1.jpg"); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); stream.Close(); 

    After closing the stream, the file will be unlocked.

    • Thanks, the solution works. But I can't replace the contents of BitmapImage a second time. Can you tell me how to do this? - Ilya
    • one
      bitmap.Dispose (); - Garrus_En