Load a BitmapSource and save using the same name in WPF -> IOException

后端 未结 5 771
太阳男子
太阳男子 2020-12-21 00:53

When I try to save a BitmapSource that I loaded earlier, a System.IO.IOException is thrown stating another process is accessing that file and the filestream can

5条回答
  •  时光取名叫无心
    2020-12-21 01:29

    Inspired by the comments I got on this issue, I solved the problem by reading all bytes into a memorystream and using it as the BitmapImage's Sreamsource.

    This one works perfectly:

    if (File.Exists(filePath))
    {
        MemoryStream memoryStream = new MemoryStream();
    
        byte[] fileBytes = File.ReadAllBytes(filePath);
        memoryStream.Write(fileBytes, 0, fileBytes.Length);
        memoryStream.Position = 0;
    
        image.BeginInit();
        image.StreamSource = memoryStream;
    
        if (decodePixelWidth > 0)
            image.DecodePixelWidth = decodePixelWidth;
    
        image.EndInit();
    }
    

提交回复
热议问题