如何删除文件,该文件由另一个使用C#的进程使用 [英] How to delete file and that file is used by another process using C#

查看:603
本文介绍了如何删除文件,该文件由另一个使用C#的进程使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#应用​​程序中,我想在下面的场景中删除文件。

In my C# application I want to delete file in below scenario.


  1. OpenFileDialog并选择任何.jpg文件。

  1. OpenFileDialog and select any .jpg file.

在PictureBox中显示该文件。

Display that file in PictureBox.

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

Delete that file if needed.

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

I already try while doing step 3 I set default Image to PictureBox just before delete but that is not work.

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

How can I delete file? Please suggest me.

 // 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);
        }
 }


推荐答案

更换图像听起来不错 - 但不要忘记处理旧的 图像 仍然保持文件打开(默认情况下,将保持文件图像是垃圾收集 - 在未来的某个未知时间):

Replacing the image sounds like a good idea - but don't forget to dispose of the old Image that's still holding the file open (and will, by default, until that Image is garbage collected - at some unknown time in the future):

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);
        }
 }

(也可能直接处理图像而不替换 PictureBox 的图像 - 它取决于关于删除后你还要做什么 - 例如,如果出现 PictureBox 的表格正在关闭,你可能想先让它发生然后再直接处理图像)。

(It may also be possible to Dispose of the Image directly without replacing the image for the PictureBox - it depends on what else you're going to do after deletion - e.g. if the form on which the PictureBox appears is closing that you may want to let that happen first and then just directly dispose of the image).

这篇关于如何删除文件,该文件由另一个使用C#的进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆