You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中用Verb=runas提权运行logman.exe无输出问题及解决需求

解决提权运行logman.exe并捕获输出的问题

我来帮你搞定这个问题!你遇到的核心矛盾是**Verb="runas"提权设置和RedirectStandardOutput捕获输出的冲突**:

  • 要通过Verb="runas"请求管理员权限,必须把UseShellExecute设为true(这是Windows Shell处理提权的硬性要求);
  • 但RedirectStandardOutput这类捕获输出的属性,强制要求UseShellExecute必须为false。

这两个设置互斥,所以你的原有代码没法直接捕获提权进程的输出。下面是可行的解决方案:通过将logman的输出重定向到临时文件,等提权进程运行完成后读取文件内容来获取结果。

修改后的代码示例

using System;
using System.IO;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // 创建临时文件存储logman的输出
        string tempOutputPath = Path.GetTempFileName();
        try
        {
            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "logman.exe",
                    // 把输出和错误都重定向到临时文件,保留原有参数
                    Arguments = $"PerfCounterCustom > \"{tempOutputPath}\" 2>&1",
                    Verb = "runas",
                    CreateNoWindow = true,
                    UseShellExecute = true // 提权必须设置为true
                }
            };

            process.Start();
            process.WaitForExit();

            // 读取临时文件里的输出内容
            if (File.Exists(tempOutputPath))
            {
                foreach (string line in File.ReadAllLines(tempOutputPath))
                {
                    if (line.Contains("Root Path:"))
                    {
                        Console.WriteLine(line.Trim());
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            // 清理临时文件,避免残留
            if (File.Exists(tempOutputPath))
            {
                try
                {
                    File.Delete(tempOutputPath);
                }
                catch
                {
                    // 忽略删除失败,系统会自动清理临时文件
                }
            }
        }
    }
}

关键修改点说明

  • 输出重定向到文件:在Arguments里添加> "{tempOutputPath}" 2>&1",把标准输出和错误输出都写入临时文件;
  • 保留UseShellExecute=true:满足Verb="runas"的提权要求;
  • 读取临时文件:进程退出后读取文件内容,筛选你需要的"Root Path:"行;
  • 清理临时文件:在finally块中删除临时文件,避免垃圾残留。

另外要注意:如果用户拒绝UAC提权弹窗,进程会启动失败,代码里的catch块会捕获到对应异常,你可以根据需求添加提示逻辑。

内容的提问来源于stack exchange,提问作者user584018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:26:24