如何使用 windows 应用程序启动控制台应用程序并读取(监视)命令行 - 在 C# 中实时逐行

how to start console application with windows application and read (monitoring) command line - line by line real time in c#

我有一个控制台应用程序,它逐行生成行: 数据1 数据2 数据3 ... 当它的命令行被清除时,它会无限重复(数据可以改变) 我必须实时观察控制台应用程序的命令行 windows 应用程序并处理行数据(例如将其保存以逐行列出牛)!有可能吗?

您基本上需要订阅该控制台应用程序的输出流,以便能够在控制台上打印每一行。

您需要做的是创建 Windows Forms 应用程序(WPF 也可以)并从那里启动控制台应用程序。

如果您不想将当前的控制台应用程序显示为可见 window,请记住将 CreateNoWindow 设置为 true。

启动控制台应用程序的方法如下:

var processStartInfo = new ProcessStartInfo(fileName, arguments);
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
processStartInfo.RedirectStandardOutput = true; // We handle the output
processStartInfo.CreateNoWindow = true; // If you want to hide the console application so it only works in the background.

// Create the actual process
currentProcess = new Process();
currentProcess.EnableRaisingEvents = true;
currentProcess.StartInfo = processStartInfo;

// Start the process
bool processDidStart = currentProcess.Start();

我们需要一个 BackgroundWorker 来在后台读取控制台应用程序的输出。

outputReader = TextReader.Synchronized(currentProcess.StandardOutput);
outputWorker.RunWorkerAsync();

现在您可以实时获取控制台应用程序的所有输出,并使用它来创建列表或您想要的任何内容。

void outputWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Work until cancelled
    while (outputWorker.CancellationPending == false)
    {
        int count = 0;
        char[] buffer = new char[1024];
        do
        {
            StringBuilder builder = new StringBuilder();

            // Read the data from the buffer and append to the StringBuilder
            count = outputReader.Read(buffer, 0, 1024);
            builder.Append(buffer, 0, count);

            outputWorker.ReportProgress(0, new OutputEvent() { Output = builder.ToString() });
        } while (count > 0);
    }
}

已处理的数据可通过 BackgroundWorker 的 ProgressChanged 事件获得。

void outputWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (e.UserState is OutputEvent)
    {
        var outputEvent = e.UserState as OutputEvent;

        /* HERE YOU CAN USE THE OUTPUT LIKE THIS:
         * outputEvent.Output
         *
         * FOR EXAMPLE:
         * yourList.Add(outputEvent.Output);
         */
    }
}

以上代码是从以下 Codeproject.com 文章中提取并修改为您的目的,以防将来它不再存在:Embedding a Console in a C# Application.