2012-12-27 125 views
2

我想刪除一個文件。但它不能做,因爲它使用另一個過程。 錯誤消息:如何在關閉C文件進程後刪除文件#

"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 [email protected]"; 
      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); 
     } 
    } 

請給我一個刪除文件部分的解決方案。 謝謝!

+7

'result.ToString()。Equals(「Yes」)' - 痛苦!使用'result == DialogResult.Yes'。 – dialer

+0

您必須確定哪個進程已鎖定文件,並讓它釋放其鎖(或終止進程)。它*是*可能關閉其他進程文件句柄(應用程序'解鎖'這樣做,例如),但它不是微不足道的。 –

+2

你可以使用ResourceMonitor或者進程資源管理器來查看打開的文件句柄 – makc

回答

1

這裏的錯誤信息告訴你所有你需要知道的東西 - 持有你的文件,所以你不能刪除它。

您是否在應用程序的其他位置打開了文件,並且沒有正確關閉文件流?

+0

Thakn you @BrianC。但我沒有使用FileStream。我只在PictureBox中顯示覆制的圖像。此後PictureBox.Image = null;我試圖刪除通用文件夾中的圖像。但它不能。這個複製的圖像不被使用另一個進程。它的唯一展示在picturebox中。但是在刪除文件之前我清除了picturebox。但它不起作用。無論如何謝謝你! – Himesh

0

嘗試處理圖像在PictureBox

PictureBox.Image.Dispose();