【发布时间】:2019-03-11 21:35:00
【问题描述】:
我有一个正在 WPF 中编写的应用程序。这很简单,我有这个字符串类型的属性,它读取图像文件 (.png) 的路径并检查它的分辨率。如果 dpi 不是 96,那么它将分辨率设置为 96。简单。好吧,我完成了那部分,但是,当我必须删除旧文件并将其保存为具有正确分辨率的文件时,我收到一条错误消息:
System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.'
这就是我在代码中所做的。这是在我的 ViewModel 中
private string _bkImage = "";
public virtual string BkImage
{
get {return _bkImage ;}
set{
FileStream stream = new FileStream(value, FileMode.Open, FileAccess.Read);
Bitmap bmpFromFile = (Bitmap)System.Drawing.Image.FromFile(stream.Name);
if(Math.Round(bmpFromFile.HorizontalResolution) != 96 && Math.Round(bmpFromFile.VerticalResolution) != 96)
{
bmpFromFile.SetResolution(96, 96);
File.Delete(stream.Name); //This is where I get the error
bmpFromFile.Save($"{stream.Name}");
bmpFromFile.Dispose();
}
control.Image.Source = new BitmapImage(new Uri(stream.Name)); //assigning the new image here
//... more non-related code here
}
}
我被这个错误难住了。我在做一些不正常的事情吗?非常感谢。
【问题讨论】:
-
抱歉,您的代码一团糟。您没有在视图模型属性的设置器中认真设置 Image 元素的 Source 属性吗?为什么要更改位图分辨率,而不是简单地调整 Image 元素的大小?
-
System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.'在您的情况下意味着您在当前进程中使用此文件。因此,您需要在尝试删除文件之前关闭/处置所有访问该文件的内容。在你的情况下,我相信它是stream。 -
@tukaef 不,它是保持文件打开的 BitmapImage。