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

问题原因:

WPF 打开本地图片,同时另一个进程去访问这个图片;

1
2
3
4
5
6
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(filePath);
bitmap.EndInit();
 
Image currentImage .Source = bitmap;

此时提升:正由另一进程使用,因此该进程无法访问该文件”

尝试了很多方法,都不成功,最终解决方案如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 把图片写进 byte[] 缓存
FileStream fs = new FileStream(icoPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
br.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] bytes = br.ReadBytes((int)br.BaseStream.Length);
//释放资源
br.Close();
fs.Close();
fs.Dispose();
 
 
// 把byte[] 缓存作为图片资源
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(bytes);
bitmap.EndInit();
 
Image currentImage .Source = bitmap;

  

  

  

posted @   microsoft-zhcn  阅读(594)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示