我有一个表格,OpenFileDialog
用于选择图像并将其显示在pictureBox
. 在表单打开之前,用户可以根据需要多次打开并保存打开的图像。我想要做的是,在每次新的选择保存后,删除以前保存的图像(如果有的话)。问题是,当我现在实现代码时,我可以第一次删除图像,如果我继续使用当前打开的表单保存图像,我会收到资源正在使用的错误。我所做的是Dispose()
图像,但我想我没有在正确的地方做。
这是我打开和加载图像的方式:
private void btnExplorer_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select file";
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = fileNameFilter;
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = prefixFilter;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox1.InitialImage = new Bitmap(openFileDialog1.FileName);
pictureBox1.ImageLocation = openFileDialog1.FileName;
selectedFile = pictureBox1.ImageLocation;
selectedFileName = openFileDialog1.SafeFileName;
pictureBox1.Load();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
MessageBox.Show("Error loading image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
在同一个课程中,如果我需要删除旧图像,我会调用这个方法:
public void DeleteImage(AppConfig imagePath, string ImageName)
{
pictureBox1.InitialImage.Dispose();//Release the image before trying to delete it
string imgPath = imagePath.ConfigValue.ToString();
File.Delete(imgPath + "\\" + ImageName);
}
如你看到的。该Dispose()
方法就在这里,尽管我将确保在尝试删除资源之前将其处理掉,但正如我所说,这只工作一次,然后我得到的错误次数与我尝试保存图像的次数一样多。
附言
我得到的确切错误是:
The process cannot access the file 'C:\Images\ME_083a210e1a7644198fe1ecaceb80af52.jpg' because it is being used by another process.