温馨提示×

C#子进程的输出如何捕获

c#
小樊
83
2024-08-27 09:55:06
栏目: 编程语言

在C#中,可以使用System.Diagnostics.Process类来创建和管理子进程

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

class Program
{
    static void Main(string[] args)
    {
        // 创建一个新的ProcessStartInfo对象,用于配置子进程
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe", // 指定要运行的程序(例如:cmd.exe)
            RedirectStandardOutput = true, // 重定向标准输出,以便我们可以捕获它
            UseShellExecute = false, // 不使用操作系统shell启动进程
            CreateNoWindow = true // 不创建新窗口
        };

        // 创建一个新的Process对象,用于管理子进程
        Process process = new Process
        {
            StartInfo = startInfo
        };

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

        // 读取子进程的输出
        string output = process.StandardOutput.ReadToEnd();

        // 等待子进程退出
        process.WaitForExit();

        // 输出子进程的输出
        Console.WriteLine("子进程输出:");
        Console.WriteLine(output);
    }
}

这个示例将创建一个新的子进程,该子进程运行cmd.exe。通过设置RedirectStandardOutputtrue,我们可以捕获子进程的输出。然后,我们使用process.StandardOutput.ReadToEnd()方法读取子进程的输出,并将其输出到控制台。

0