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

C#中如何实时获取命令行Process的运行输出?

实时捕获命令行进程输出的解决方案

要实现实时获取命令行进程的输出(比如进度百分比),核心是用异步方式读取输出,同时保证主线程不会提前终止。以下是具体实现步骤和代码示例(以C#为例):

关键要点

  • 必须开启输出重定向,并禁用Shell执行
  • 通过异步事件处理实时输出,避免阻塞
  • 保持主线程存活,直到进程执行完成

完整代码示例

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // 配置进程启动信息
        var startInfo = new ProcessStartInfo
        {
            FileName = "your-command.exe", // 替换为你的目标命令行程序
            Arguments = "your-run-arguments", // 替换为程序运行参数
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            StandardOutputEncoding = System.Text.Encoding.UTF8 // 匹配目标程序的输出编码
        };

        using var process = new Process { StartInfo = startInfo };

        // 绑定输出事件,实时打印内容
        process.OutputDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Console.WriteLine($"进程输出: {e.Data}");
            }
        };

        // 绑定错误输出事件
        process.ErrorDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Console.WriteLine($"进程错误: {e.Data}");
            }
        };

        // 启动进程
        process.Start();

        // 启动异步读取输出(关键:非阻塞式捕获输出)
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        // 等待进程结束,主线程在此期间不会终止,异步输出会持续触发
        process.WaitForExit();

        // 如果是GUI程序或不需要等待进程结束,可替换为其他主线程等待逻辑,比如:
        // Console.ReadLine();
    }
}

注意事项

  • 如果目标程序的输出是无缓冲的(比如不换行直接输出进度),需要改用StandardOutput.BaseStream读取字节流,而非行事件
  • 务必匹配目标程序的输出编码,否则会出现乱码(比如GBK编码的程序要设置Encoding.GetEncoding("GBK"))
  • 若移除WaitForExit(),主线程会直接结束,子进程会被系统终止,因此必须通过WaitForExit()、Console.ReadLine()等方式让主线程保持运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:57:15