PictureBox加载图片后,再将Image属性值设置为null,但本地图片仍无法删除,提示文件正被另一个程序使用,相关代码:
复制内容到剪贴板程序代码
//显示图片
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(@"f:\demo.gif");
}
//不显示图片
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
}
究其原因应是Image属性值设置为null,但资源仍未释放,需等垃圾回收器回收,那我们就手动释放资源再测试下:
复制内容到剪贴板程序代码
//显示图片
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(@"f:\demo.gif");
}
//不显示图片并释放资源
private void button2_Click(object sender, EventArgs e)
{
Image image = pictureBox1.Image;
pictureBox1.Image = null;
image.Dispose();
}
终于可以删除了!但如果图片在使用中时试图删除图片,上边代码又不行了,解决方法是将本地图片读到内存流(相当于复制一份图片),再将内存流转化为Image对象并绑定到PictureBox的Image属性,这样原图可正常删除,代码如下:
复制内容到剪贴板程序代码
//显示图片
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = GetFile(@"f:\demo.gif");
}
//不显示并释放资源
private void button2_Click(object sender, EventArgs e)
{
Image image = pictureBox1.Image;
pictureBox1.Image = null;
image.Dispose();
}
///
/// 将文件转为内存流
///
///
///
private MemoryStream ReadFile(string path)
{
if (!File.Exists(path))
return null;
using (FileStream file = new FileStream(path, FileMode.Open))
{
byte[] b = new byte[file.Length];
file.Read(b, 0, b.Length);
MemoryStream stream = new MemoryStream(b);
return stream;
}
}
///
/// 将内存流转为图片
///
///
///
private Image GetFile(string path)
{
MemoryStream stream = ReadFile(path);
return stream == null ? null : Image.FromStream(stream);
}
原文链接:https://blog.csdn.net/jinhongdu/article/details/7703251