【问题标题】:How to delete file after closed that file process in C#在C#中关闭该文件进程后如何删除文件
【发布时间】:2012-12-27 13:50:08
【问题描述】:

我想删除一个文件。但它不能这样做,因为它使用另一个进程。 错误信息:

"The process cannot access the file '*file path\4.JPG*' because it is being used by another process."  

我的程序的描述是,假设我将图像复制到一个公共文件中。然后如果我想从公共文件夹中删除这个图像,则会生成错误消息。 file.Delete(..) 在我的代码中不起作用。

    private void btnDelete_Click(object sender, EventArgs e)
    {
        DialogResult result = MessageBox.Show("Are you sure do you want to delete this recorde?","Delete",MessageBoxButtons.YesNo,MessageBoxIcon.Question);

        if (result.ToString().Equals("Yes"))
        {
            string deleteQuery = "DELETE FROM dbo.fEmployee WHERE EmpId=@empId";
            SqlParameterCollection param = new SqlCommand().Parameters;
            param.AddWithValue("@empId",cmbEmpIdD.SelectedValue);
            int delete = _dataAccess.SqlDelete(deleteQuery,param);
            if (delete>0)
            {
                **ImageDeletion();**
                MessageBox.Show("Recorde Deleted sucessfully.","Delete",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
            else if (delete.Equals(0))
            {
                 MessageBox.Show("Recorde is not deleted.","Falied",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
    }


    private void ImageDeletion()
    {
        string ext;
        ext = Path.GetExtension(txtImgPathD.Text.Trim());
        if (!string.IsNullOrWhiteSpace(ext))
        {
            string path = appPath + @"\" + @"EmployeeImages\" + cmbEmpId.SelectedValue.ToString().Trim() + ext;
            PictureBox.InitialImage = null;
            PictureBox.Invalidate();
            PictureBox.Image = null;
            PictureBox.Refresh();
            File.Delete(path);
        }
    }

请给我一个删除文件部分的解决方案。 谢谢!

【问题讨论】:

  • result.ToString().Equals("Yes") - 痛苦!使用result == DialogResult.Yes
  • 您必须确定哪个进程锁定了文件并让它释放它的锁定(或终止进程)。 可以关闭其他进程文件句柄(例如,应用程序'Unlocker'会这样做),但这并非易事。
  • 您可以使用 ResourceMonitor 或 proccess explorer 查看打开的文件句柄
  • 因为这个问题显然还没有解决:你需要先告诉我们你的程序是如何打开图像文件的,否则我们只能猜测。
  • 向我们展示您如何打开图像文件。

标签: c# file


【解决方案1】:

此处的错误消息告诉您所有您需要知道的信息 - 某些东西保留了您的文件,因此您无法删除它。

您是否在应用程序的其他地方打开了文件,并且没有正确关闭文件流?

【讨论】:

  • 谢谢@BrianC。但我没有使用 FileStream。我只在 PictureBox 中显示复制的图像。在此之后 PictureBox.Image = null;我试图在公共文件夹中删除该图像。但它不能。此复制的图像未用于其他进程。它只显示在图片框中。但我在删除文件之前清除了图片框。但它不工作。无论如何,非常感谢!
【解决方案2】:

尝试在PictureBox 中处理图像。

PictureBox.Image.Dispose();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多