代码之家  ›  专栏  ›  技术社区  ›  abatishchev Karl Johan

提升权限不适用于UseShellExecute=false

  •  16
  • abatishchev Karl Johan  · 技术社区  · 14 年前

    我想用提升的权限启动一个子进程(实际上是同一个控制台应用程序),但要隐藏窗口。

    下一步我做:

    var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location)
    {
        UseShellExecute = true, // !
        Verb = "runas", 
    };
    
    var process = new Process
    {
        StartInfo = info
    };
    
    process.Start();
    

    这是有效的:

    var identity = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    identity.IsInRole(WindowsBuiltInRole.Administrator); // returns true
    

    UseShellExecute = true 创建一个新窗口,我也不能重定向输出。

    所以当我下一步做的时候:

    var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location)
    {
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        UseShellExecute = false, // !
        Verb = "runas"
    };
    
    var process = new Process
    {
        EnableRaisingEvents = true,
        StartInfo = info
    };
    
    DataReceivedEventHandler actionWrite = (sender, e) =>
    {
        Console.WriteLine(e.Data);
    };
    
    process.ErrorDataReceived += actionWrite;
    process.OutputDataReceived += actionWrite;
    
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
    

    这不会提升特权,并且上面的代码返回false。为什么?

    3 回复  |  直到 14 年前
        1
  •  21
  •   Community    7 年前

    好吧,这就是为什么它不起作用。不确定禁止启动绕过UAC的隐藏进程是否是故意的。可能。 非常 可能。

    检查 this Q+A

        2
  •  9
  •   tpol    8 年前

    在我的例子中,一旦提升的子进程完成,就可以获得输出。这是我想出的解决办法。它使用临时文件:

    var output = Path.GetTempFileName();
    var process = Process.Start(new ProcessStartInfo
    {
        FileName = "cmd",
        Arguments = "/c echo I'm an admin > " + output, // redirect to temp file
        Verb = "runas", // UAC prompt
        UseShellExecute = true,
    });
    process.WaitForExit();
    string res = File.ReadAllText(output);
    // do something with the output
    File.Delete(output);
    
        3
  •  0
  •   Community    7 年前

    检查 this answer .

    Named Pipes 当您可以访问子进程的源代码时。