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

您所在的位置:网站首页 arcgis导入数据库时dbf正由另一进程使用 WPF “正由另一进程使用,因此该进程无法访问该文件”的问题&解决方法

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

2024-04-06 08:51| 来源: 网络整理| 查看: 265

转自: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 fileBinaryReader binReader = new BinaryReader(File.Open(filePath, FileMode.Open));FileInfo fileInfo = new FileInfor(filePath);byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);binReader.Close();

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

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3