Search code examples
wpfimageimagesource

On changing the ImageSource of the Image using file picker, pop up raised that the file is in use


I am having an Image with default ImageSource, on picking up the new image using file picker it loads fine then on again the picking the previously used file, pop up raised that the file is still in use. When every time a new image is picked, it is working fine. Is there any way to close or dispose the previously picked file or its ImageSource?

 <Image x:Name="image" Source="Assets\RoadView.jpeg"></Image>

  private void change_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Image Files ( *.png, *.bmp *.jpg, *.gif, *.tif)|*.png;*.bmp;*.jpg;*.gif;*.tif";
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

        if (openFileDialog.ShowDialog() == true)
        {
            Stream stream = File.Open(openFileDialog.FileName, FileMode.Open);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = stream;
            bitmapImage.EndInit();
            image.Source = bitmapImage;
        }
    }

Solution

  • You don't close the FileStream, hence the file is kept open and can't be opened a second time.

    The easiest way to close the FileStream is to dispose of the object by means of a using block. In order to load the BitmapImage immediately before closing the stream, you also need to set BitmapCacheOption.OnLoad.

    var bitmapImage = new BitmapImage();
    
    using (var stream = File.Open(openFileDialog.FileName, FileMode.Open))
    {
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
    }
    
    image.Source = bitmapImage;