Loading

使用c#检测文件正在被那个进程占用

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

简单而有效。

posted @ 2015-01-13 17:07  jevan  阅读(7867)  评论(4编辑  收藏  举报