处理图像的适当位置在哪里

Ler*_*ica 0 c# dispose picturebox winforms

我有一个表格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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

在同一个类中,我有这个方法,如果我需要删除旧图像,我会调用它:

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);
        }
Run Code Online (Sandbox Code Playgroud)

如你看到的.这个Dispose()方法在这里,我会确保资源将在尝试删除它之前处理,但正如我所说,这只工作一次,然后我得到错误的次数与保存图像的尝试次数相同.

PS

我得到的确切错误是:

The process cannot access the file 'C:\Images\ME_083a210e1a7644198fe1ecaceb80af52.jpg' because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)

Vla*_*adL 5

有一种更好的方法.使用FileStream加载图像,然后将其分配给pictureBox

FileStream bmp = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
Image img = new Bitmap(bmp);
pictureBox1.Image = img;
bmp.Close();
Run Code Online (Sandbox Code Playgroud)

如果你想清除图片框,简单地说

pictureBox1.Image = null;
Run Code Online (Sandbox Code Playgroud)