要检测文件被那个进程占用,需要使用微软提供的工具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+)(d+)(?=s+)"; foreach(Match match in Regex.Matches(outputTool, matchPattern)) { Process.GetProcessById(int.Parse(match.Value)).Kill(); }
简单而有效。