前台用image的source属性引用图片路径(如:“F:/Pic_近景图.jpg”),程序连接设备,当识别到图片时,用文件流FileStream写入到source路径下,当程序走到fileStream时报错:
文件xxx.jpg 正由另一进程使用,因此该进程无法访问此文件
该如何解决,网上说是image资源未释放的问题,求解决办法!!
"F:/Pic_近景图.jpg"
->
"F:\\Pic_近景图.jpg"
使用try-finally格式,避免中间代码异常时没有执行close方法
FileStream fs = new FileInputStream(str);
try{
...
}finally{
if(fs != null){
fs.close();
}
}
首先在代码所在的项目中新建放置图片的文件夹,把图片放入其中:
设置图片属性:
代码调整为:
string FilePath=AppDomain.CurrentDomain.BaseDirectory + @"文件夹名称\Pic_近景图.jpg";
System.IO.Stream oldstream = new FileStream(FilePath, FileMode.Open);
楼主,试试这个看看。
FileStream fs = new FileStream(str, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.UriSource = new Uri(图片路径);
bitmapImage.EndInit();
bitmapImage.Freeze();
var filePath = "F:\文件路径";
FileStream fs = File.OpenRead(filePath);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
bitmapImage.Freeze();