原文地址:http://www.cnblogs.com/pdfw/archive/2008/03/25/1121787.html
imageEditImage是一个Image控件,在后台代码中我想给它指定Source的属性。我先如下方式进行:
BitmapImage image = new BitmapImage(new Uri(strImagePath, UriKind.Absolute));imageEditImage.Source = image;
strImagePath是图片的绝对路径。
在另一处代码中我想把strImagePath指定的图片删掉,操作如下:
if (System.IO.File.Exists(strImagePath))
{
System.IO.File.Delete(strImagePath);
}
但是删除操作报错,大意是程序在使用图片文件。
解决方法如下:
BitmapImage image = new BitmapImage();
m_ImageStream = new FileStream(strImagePath, FileMode.Open);
image.BeginInit();
image.StreamSource = m_ImageStream;
image.EndInit();
imageEditImage.Source = image;
其中m_ImageStream是一个全局的Stream变量,在删除操作前关闭这个变量就不会再出错了。代码改动如下:
if (m_ImageStream != null)
{
m_ImageStream.Close();
m_ImageStream.Dispose();
}
if (System.IO.File.Exists(strImagePath))
{
System.IO.File.Delete(strImagePath);
}
本文介绍了一种在WPF应用程序中处理图片显示与删除冲突的方法。通过使用FileStream和BitmapImage组件并确保在删除图片前正确关闭相关流,避免了因图片被程序占用而导致的删除失败问题。
3922

被折叠的 条评论
为什么被折叠?



