問題描述
當我嘗試保存我之前加載的 BitmapSource 時,會拋出一個 System.IO.IOException
,指出另一個進程正在訪問該文件并且無法打開文件流.
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 cannot be opened.
如果我只保存而不提前加載,一切正常.
If I only save whithout loading earlier, everything works fine.
加載代碼:
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = uri;
if (decodePixelWidth > 0)
image.DecodePixelWidth = decodePixelWidth;
image.EndInit();
保存代碼:
using (FileStream fileStream = new FileStream(Directory + "\" + FileName + ".jpg", FileMode.Create))
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)image));
encoder.QualityLevel = 100;
encoder.Save(fileStream);
}
似乎在加載圖像數據后,文件仍然被鎖定并且永遠不會被覆蓋,而打開它的應用程序仍在運行.任何想法如何解決這個問題?非常感謝您提供任何解決方案.
It seems like after loading the image data, the file is still locked an can never be overwritten while the application who opened it is still running. Any ideas how to solve this? Thanks alot for any solutions.
推薦答案
受到我對這個問題的評論的啟發,我通過將所有字節讀入內存流并將其用作 BitmapImage 的 Sreamsource 來解決該問題.
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.
這個很完美:
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();
}
這篇關于加載一個 BitmapSource 并在 WPF 中使用相同的名稱保存 ->IO異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!