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



我有一个控制台应用程序,逐行生成行:Data1Data2Data3…当它的命令行被清除时,它会无限地重复(数据可以改变)。我必须用windows应用程序实时观察控制台应用程序的命令行,并为行数据工作(例如,将其保存到列表中逐行)!有可能吗?

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

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

如果你不想将当前控制台应用程序显示为可见窗口,请记住将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文章,并根据您的目的进行修改,以防将来它不再存在:

最新更新