冰楓論壇

標題: [C#] 檢測檔案被什麼程式占住並關閉占住的程式 [打印本頁]

作者: whitefox    時間: 2023-7-8 19:35
標題: [C#] 檢測檔案被什麼程式占住並關閉占住的程式
查詢被什麼程式占住需要使用軟體的工具 Handle.exe
按此下載 Handle v5.0

這個例子假設 Handle.exe 放在同一個目錄下
可以嘗試開啟 pdf/doc/jpg/bmp 等檔案再檢測就可以看到效果
  1. // 要檢測的檔案
  2. string TestFile = @"c:\testfile.pdf";

  3. Process pTool = new Process();
  4. pTool.StartInfo.FileName = "handle.exe";
  5. pTool.StartInfo.Arguments = TestFile + " /accepteula";
  6. pTool.StartInfo.UseShellExecute = false;
  7. pTool.StartInfo.RedirectStandardOutput = true;
  8. pTool.Start();           
  9. pTool.WaitForExit();
  10. string outputTool = pTool.StandardOutput.ReadToEnd();

  11. // 使用正則表示篩選出占住程式的 PID
  12. string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
  13. foreach(Match match in Regex.Matches(outputTool, matchPattern))
  14. {
  15.     Process.GetProcessById(int.Parse(match.Value)).Kill();
  16. }
複製代碼





歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓