从代码执行时,Handle.exe无法正常工作

时间:2012-10-11 21:36:45

标签: c# file-io file-locking

我正在尝试使用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,因此我通过代码启动的任何进程都获得相同的权限。当然这只是在调试时,但我需要至少让它在一个环境中工作,然后再担心其他人。

运行句柄后,outputTool

Handle v3.5
Copyright (C) 1997-2012 Mark Russinovich
Sysinternals - www.sysinternals.com

No matching handles found.

2 个答案:

答案 0 :(得分:2)

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

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

您可以添加将requestedExecutionLevel设置为requireAdministrator的应用程序清单,以确保您的应用始终处于提升状态。

答案 1 :(得分:0)

我已经弄明白了。我的文件路径有一个额外的&#39; \&#39;。显然这会混淆句柄,但不是File.Open(...)

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

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

我想因为我从未在我的问题中包含文件路径,所以其他任何人都无法弄明白。对不起SO用户。

相关问题