2

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

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

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

4

2 回答 2

1

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

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

于 2012-12-27T13:53:30.043 回答
0

尝试将图像放置在PictureBox.

PictureBox.Image.Dispose();
于 2012-12-28T16:55:26.463 回答