有一個古老的傳說:
占用的文件是可以被強制刪除的。。。
如果被別的應用程序打開着,你就要先找到那個打開的程序,結束掉才行。或者關閉關閉相關進程,延遲的方法。
一般來說被占用就意味着有其它進行或者線程對該文件讀或寫操作。如果是自己的程序對該文件有文件流讀寫最好在完成或者異常的時候關閉流Close(),釋放流Dispose(),后續才不會提示對此文件有占用;如果不是自己的程序原因引起文件的占用,則要重啟一下電腦進行刪除,如果仍然提示占用則要結束掉占用此文件的進程,才可以進行刪除。
解決方案1
要檢測文件被那個進程占用,需要使用微軟提供的工具Handle.exe,這里有微軟提供的下載
我們可以在c#中調用Handle.exe 來檢測到底哪個進程占用了文件
string fileName = @"c:\aaa.doc";//要檢查被那個進程占用的文件 Process tool = new Process(); tool.StartInfo.FileName = "handle.exe"; tool.StartInfo.Arguments = fileName+" /accepteula"; tool.StartInfo.UseShellExecute = false; tool.StartInfo.RedirectStandardOutput = true; tool.Start(); tool.WaitForExit(); string outputTool = tool.StandardOutput.ReadToEnd(); string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)"; foreach(Match match in Regex.Matches(outputTool, matchPattern)) { Process.GetProcessById(int.Parse(match.Value)).Kill(); }
參考文章