这个问题(以前)接受的答案是非常糟糕的做法。如果你阅读文档 on System.Drawing.Bitmap
,特别是对于从文件创建位图的重载,您会发现:
文件保持锁定状态,直到位图被释放。
在您的代码中,您创建位图并将其存储在局部变量中,但完成后您永远不会释放它。这意味着您的图像对象已超出范围,但尚未释放其对您尝试删除的图像文件的锁定。对于所有实现的对象IDisposable
(like Bitmap
)您必须自行处理它们。看这个问题例如(或搜索其他人 - 这是一个非常重要的概念!)。
要正确纠正问题,您只需在使用完图像后将其处理掉即可:
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName); // create the bitmap
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose(); // dispose the bitmap object
}
请不要采纳下面答案中的建议 - 您几乎不需要打电话GC.Collect
如果你需要这样做才能让事情顺利进行,那么这应该是一个非常强烈的信号,表明你做错了其他事情。
另外,如果您只想删除one文件(您显示的位图)您的删除代码是错误的,并且也会删除目录中的每个文件(这只是重复阿德尔的观点)。此外,与其保持全球性OpenFileDialog
对象存活只是为了存储文件名,我建议摆脱它并仅保存文件信息:
FileInfo imageFileinfo; //add this
//OpenFileDialog ofd = null; Get rid of this
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
OpenFileDialog ofd = new OpenFileDialog(); //make ofd local
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
imageFileinfo = new FileInfo(ofd.FileName); // save the file name
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose();
}
ofd.Dispose(); //don't forget to dispose it!
}
else
{
return;
}
}
然后在第二个按钮处理程序中,您可以删除您感兴趣的一个文件。
private void button2_Click(object sender, EventArgs e)
{
if (!IsFileLocked(imageFileinfo))
{
imageFileinfo.Delete();
}
}