【发布时间】: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 查看打开的文件句柄
-
因为这个问题显然还没有解决:你需要先告诉我们你的程序是如何打开图像文件的,否则我们只能猜测。
-
向我们展示您如何打开图像文件。