如何删除文件并且该文件被另一个使用C#的进程使用

How to delete file and that file is used by another process using C#

在我的 C# 应用程序中,我想在以下情况下删除文件。

  1. OpenFileDialog 和 select 任何 .jpg 文件。

  2. 在 PictureBox 中显示该文件。

  3. 如果需要,请删除该文件。

我已经在执行第 3 步时尝试过,我在删除之前将默认图像设置为 PictureBox,但这不起作用。

如何删除文件?请建议我。

 // Code for select file.
 private void btnSelet_Click(object sender, EventArgs e)
 {
        if (DialogResult.OK == openFileDialog1.ShowDialog())
        {
            txtFileName.Text = openFileDialog1.FileName;
            myPictureBox.Image = Image.FromFile(openFileDialog1.FileName);
        }
 }

 // Code for Delete file
 private void btnDelete_Click(object sender, EventArgs e)
 {
        try
        {
            //myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
            System.IO.File.Delete(txtFileName.Text);
            MessageBox.Show("File Delete Sucessfully");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
 }

替换图像听起来是个好主意 - 但不要忘记处理仍然保持文件打开状态的旧 Image(默认情况下,直到 Image垃圾收集 - 在未来的某个未知时间):

private void btnDelete_Click(object sender, EventArgs e)
 {
        try
        {
            var old = myPictureBox.Image;
            myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
            old.Dispose();

            System.IO.File.Delete(txtFileName.Text);
            MessageBox.Show("File Delete Sucessfully");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
 }

(也可以直接 ImageDispose 而无需替换 PictureBox 的图像 - 这取决于您在删除后要做什么- 例如,如果出现 PictureBox 的表单正在关闭,您可能希望先让它发生,然后直接处理图像)。