要检测文件被那个进程占用,需要使用微软提供的工具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();
}

简单而有效。

相关文章:

  • 2021-09-07
  • 2022-01-12
  • 2022-12-23
  • 2021-11-21
  • 2021-06-03
  • 2021-11-21
猜你喜欢
  • 2021-12-12
  • 2022-12-23
  • 2021-11-21
  • 2021-11-21
  • 2021-11-02
  • 2022-12-23
  • 2021-12-15
相关资源
相似解决方案