微软提供的查询进程利器:handle.exe
下载地址:https://docs.microsoft.com/zh-cn/sysinternals/downloads/handle
下面代码示例查询占用xx.doc的进程:
string fileName = @"E:\xx.doc"; Process handlePro = new Process(); handlePro.StartInfo.FileName = @"E:\handle.exe"; handlePro.StartInfo.Arguments = fileName + " /accepteula"; handlePro.StartInfo.UseShellExecute = false; handlePro.StartInfo.RedirectStandardOutput = true; handlePro.Start(); handlePro.WaitForExit(); string outputTool = handlePro.StandardOutput.ReadToEnd(); Regex reg = new Regex(@"(?<=pid:).*?(?=type:)"); foreach (Match match in reg.Matches(outputTool)) { int pid = int.Parse(match.Value.Trim()); Process pro = Process.GetProcessById(pid); string pn = pro.ProcessName; }
获得进程后可以进行后续相关的操作,kill进程等。