【发布时间】:2012-10-11 21:36:45
【问题描述】:
我正在尝试使用 handle.exe 来发现哪个进程拥有一个文件。当我通过命令行自行运行句柄时,它按预期工作。但是,当我从我的代码中执行它时,我总是会发现没有进程正在锁定文件。
我运行 Handle.exe 的代码:
Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = theFileName;
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 (System.Text.RegularExpressions.Match match in
System.Text.RegularExpressions.Regex.Matches(outputTool, matchPattern)) {
Process p = Process.GetProcessById(int.Parse(match.Value));
Console.WriteLine("Holding Process: " + p.Id);
}
我还尝试了一些其他方法来查找此 SO 问题中建议的文件所有权: Using C#, how does one figure out what process locked a file? 所有人仍然报告说没有任何东西可以控制该文件。
为了测试这些东西,我有一个单独的测试程序,基本上只是运行这个:
using (FileStream theStream = new FileStream(theFileName, FileMode.Open, FileAccess.Read, FileShare.None)) {
while (true) ;
}
编辑: 我以管理员身份运行 Visual Studio,因此我通过代码启动的任何进程都可以获得相同的权限。当然这只是在调试时,但我至少需要让它在一个环境中工作,然后再担心其他环境。
句柄运行后输出工具为
手柄 v3.5 版权所有 (C) 1997-2012 Mark Russinovich Sysinternals - www.sysinternals.com 找不到匹配的句柄。
【问题讨论】:
-
Handle.exe 需要 UAC 提升。而且你的正则表达式被破坏了,特别是如果 pid 是 5 位数字。 stackoverflow.com/questions/2348694/how-do-you-debug-a-regex
标签: c# file-io file-locking