I have a form with OpenFileDialog
for selecting image and showing it in pictureBox
. Until the form is open the user can open and then save the opened image as many times as he wants. What I want to do is, after each new selection-save, to delete the previously saved image if there is such. The problem is that as I implemented the code now I am able to delete the image the first time, if I keep on saving images with the currently open form I get an error that the resource is being used. What I do is Dispose()
the image but I guess I don't do it in the right place.
This is how I open and load the image:
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);
}
}
}
And in the same class I have this method which I call if I need to delete an old image:
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);
}
As you can see. The Dispose()
method is here which I though will ensure that the resource will be disposed before trying to delete it but as I said this only work once and then I get the error as many times as attempts to save image I make.
P.S
The exact error I get is:
The process cannot access the file 'C:\Images\ME_083a210e1a7644198fe1ecaceb80af52.jpg' because it is being used by another process.