【问题标题】:How to delete file and that file is used by another process using C#如何使用 C# 删除文件并且该文件被另一个进程使用
【发布时间】:2015-08-05 10:16:35
【问题描述】:

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

  1. OpenFileDialog 并选择任何 .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);
        }
 }

【问题讨论】:

  • 您自己的程序是否也在使用该文件或其他文件?
  • 取出图片id,关闭对话框(或根据需要更改)。删除带有 id 的文件。
  • 是我自己的程序
  • 你能发布你的代码吗?
  • @VikasRana Rana 我听不懂,请详细解释

标签: c# io filestream delete-file


【解决方案1】:

替换图像听起来是个好主意 - 但不要忘记处理仍然保持文件打开状态的旧 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);
        }
 }

(也可以直接将DisposeImage 替换为PictureBox 的图像而不替换PictureBox 的图像 - 这取决于您在删除后还要做什么 - 例如,如果PictureBox 似乎正在关闭,您可能希望先让它发生,然后直接处理图像)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多