WPF “正由另一进程使用,因此该进程无法访问该文件”的问题&解决方法 - 老有所依

时间:2024-03-09 20:37:39

WPF “正由另一进程使用,因此该进程无法访问该文件”的问题&解决方法

转自:http://hi.baidu.com/mbjcxtyzmjbdfyq/item/a94b9aff0e5de61ccf9f32eb

正在写一个手指画图的程序
C# + WPF
其中有一部分是加载外部某PNG文件,放入BitmapImage,再作为Image的Source显示在Canvas上
画了几笔之后,再存回这个PNG文件

================问题=================
BitmapImage这个对象没有Dispose方法,始终无法释放,因此在之后FileStream试图写这个文件时出现“正由另一进程使用,因此该进程无法访问该文件”的问题

BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(filePath);
bitmap.EndInit();

Image currentImage .Source = bitmap;
canvas.Children.Add(currentImage);

// Do some modification

private void ExportToPng( string path, Canvas surface)
{
if(path == null)
return;
........
using(FileStream outStream = new FileStream(path, FileMode.Create)
........
}

尝试了很多方法,包括在using FileStream之前加lock、在new FileStream的参数中加入FileAccess.ReadWrite、FileShare.ReadWrite、以及将bitmap.Clone作为currentImage的Source,都不成功


===============解决方法=============
最后发现初始化BitmapImage可以通过byte[]进行,于是只能通过将png文件读成byte[],再进行BitmapImage的初始化,就没有问题了

// Read byte[] from png file
BinaryReader binReader = new BinaryReader(File.Open(filePath, FileMode.Open));
FileInfo fileInfo = new FileInfor(filePath);
byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
binReader.Close();

// Init bitmap
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(bytes);
bitmap.EndInit();

为了更加保险,最后使用的方法中通过ref参数,将需要init的bitmap作为参数传入,方法内部生成一个temp的BitmapImage,完成Init后,bitmap = temp.Clone()