2013-10-06 102 views
0

我已經創建了一個按鈕。在按鈕的事件處理程序中,我想刪除文件夾(abc)中的所有文件。如何關閉另一個進程來釋放文件鎖定?

下面是該代碼:

private void button1_Click_1(object sender, EventArgs e) 
    { 
     MessageBox.Show("Are you sure!!!! The files in the folder will be deleted permanently"); 
     this.Close(); 
     string[] filePaths = Directory.GetFiles(@"C:\abc\"); 
     foreach (string filePath in filePaths) 
      File.Delete(filePath); 
    } 

例如,有文件夾中的Word文件,如果它被打開,我得到一個錯誤信息:

該進程無法訪問文件'C:\ abc \ New Microsoft Word Document.docx',因爲它正在被另一個進程使用。

+0

http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net有樣本可以找到持有鎖的過程。 –

+0

@gp。這是原始線程:http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use/11060322#11060322 –

回答

1

您可以使用Process類來查找該進程,強制關閉該程序,然後刪除該文件。這樣的事情...

Process [] proc Process.GetProcessesByName("winword"); 
proc[0].Kill(); 

但是我不會建議這樣做,因爲windows也不會刪除打開的文件。

+0

更多suggesstions? ??? – Pheonix

+0

謝謝@尼克希爾.......它的工作...... – Pheonix

相關問題