如何在 C# 中实时获取进程的输出?

问题描述 投票:0回答:1

我正在尝试启动一个旨在在命令行中使用的进程,并在该文件运行时获取该文件的输出。该过程有一个完成百分比,这是我希望我的程序得到的。

我试过这段代码:

Console.Write("Input file name: ");
string fileName = Console.ReadLine();

Process process = new();
process.StartInfo.FileName = @"example.exe";
process.StartInfo.Arguments = $"--file {fileName}";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;

process.OutputDataReceived += (sender, eventArgs) =>
{
    Console.WriteLine(eventArgs.Data);
};

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

但是,它只打印输出after进程已经退出(因此完成了它的工作),这违背了在它已经完成时获得完成百分比的目的。删除

process.WaitForExit()
使程序在启动后立即关闭。

c# cmd process percentage progress
1个回答
0
投票

您的“example.exe”应用程序可能不会写入任何输出。这是我一起进行的测试,以证明如果“example.exe”应用程序正在发送输出,您发布的代码有效。


启动进程和捕获消息的主程序。这是您发布的代码的副本,没有什么不同。

internal class Program
{
    static void Main(string[] args)
    {
        Console.Write("Input file name: ");
        string fileName = Console.ReadLine();

        Process process = new();
        process.StartInfo.FileName = @"example.exe";
        process.StartInfo.Arguments = $"--file {fileName}";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.CreateNoWindow = true;

        process.OutputDataReceived += (sender, eventArgs) =>
        {
            Console.WriteLine(eventArgs.Data);
        };

        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();
    }
}

一个快速测试 example.exe 应用程序,用于捕获 args 并重复写入输出。

internal class Program
{
    static void Main(string[] args)
    {

        if (args.Length > 0 && args[0] != null)
        {
            Console.Write($"Argument received: {args[0]}");
        }
        if (args.Length > 1 && args[1] != null)
        {
            Console.WriteLine($" {args[1]}");
        }

        while (true)
        {
            Console.WriteLine($"DateTime: {DateTime.Now}");
            Task.Delay(1000).Wait();
        }
    }
}

主程序控制台窗口的输出。

Input file name: abcd.txt
Argument received: --file abcd.txt
DateTime: 4 / 12 / 2023 5:45:10 PM
DateTime: 4 / 12 / 2023 5:45:11 PM
DateTime: 4 / 12 / 2023 5:45:12 PM
DateTime: 4 / 12 / 2023 5:45:13 PM
DateTime: 4 / 12 / 2023 5:45:14 PM
DateTime: 4 / 12 / 2023 5:45:15 PM
DateTime: 4 / 12 / 2023 5:45:16 PM
© www.soinside.com 2019 - 2024. All rights reserved.