码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-06-10 16:42:15      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:使用   文件   string   os   问题   for   

正在写一个手指画图的程序
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()

【转】“正由另一进程使用,因此该进程无法访问该文件”的问题&解决方法,布布扣,bubuko.com

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

标签:使用   文件   string   os   问题   for   

原文地址:http://www.cnblogs.com/ZXdeveloper/p/3779755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!