C# 主程序调用其他的Exe程序后,怎么获取其他程序的输出内容

在C#中,你可以使用System.Diagnostics.Process类来启动并与其他程序交互。如果你想获取其他程序的输出内容,需要设置一些ProcessStartInfo属性,并使用StandardOutput属性来读取输出。

以下是一个简单的例子,展示了如何调用其他的exe程序并获取其输出内容:

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        string exePath = @"path_to_the_executable.exe"; // 替换为你的exe路径
        Process process = new Process();

        process.StartInfo.FileName = exePath;
        process.StartInfo.UseShellExecute = false; // 必须设置为false以重定向输出
        process.StartInfo.RedirectStandardOutput = true; // 允许重定向标准输出
        process.StartInfo.CreateNoWindow = true; // 如果你不想显示命令行窗口

        try
        {
            process.Start();

            string output = process.StandardOutput.ReadToEnd(); // 读取输出内容

            process.WaitForExit(); // 等待进程结束

            Console.WriteLine("输出内容:");
            Console.WriteLine(output);
        }
        catch (Exception ex)
        {
            Console.WriteLine("出现错误: " + ex.Message);
        }
    }
}

在上述代码中:

我们设置了UseShellExecute为false,这是必须的,因为我们需要重定向输出。
我们设置了RedirectStandardOutput为true以允许读取输出内容。
使用process.StandardOutput.ReadToEnd()读取输出内容。
请注意,如果外部程序输出了大量的数据,ReadToEnd可能会阻塞。在这种情况下,你可能需要使用事件处理或异步读取。

猜你喜欢

转载自blog.csdn.net/weixin_38428126/article/details/133885852