【问题标题】:Handle.exe not working when exec from code从代码执行时,Handle.exe 不起作用
【发布时间】: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

找不到匹配的句柄。

【问题讨论】:

标签: c# file-io file-locking


【解决方案1】:

Handle.exe 必须提升运行才能正常运行。我怀疑如果你转储outputTool 的内容,你会发现它说“初始化错误:确保你是管理员”。

运行您自己的提升应用程序应该会自动启动提升的handle.exe,这将解决问题。不幸的是,您不能简单地修改您的应用程序以启动提升的 handle.exe。这将需要使用tool.StartInfo.Verb = "runas";,这需要tool.StartInfo.UseShellExecute = true;,这将与tool.StartInfo.RedirectStandardOutput = true; 冲突

您可以添加一个将requestedExecutionLevel 设置为requireAdministrator 的应用程序清单,以确保您的应用程序始终以升级方式启动。

【讨论】:

    【解决方案2】:

    我想通了。我的文件路径有一个额外的“\”。显然这会混淆句柄,但不会混淆File.Open(...)

    theFileName = "C:\ProgramData\MyApp\\imagefile.tiff"
    

    每当我尝试在 Windows cmd 中运行 handle.exe 时,我都没有包含额外的“\”。

    我想因为我从未在我的问题中包含文件路径,所以其他人不可能弄清楚。对不起 SO 用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 2018-10-19
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      相关资源
      最近更新 更多