【问题标题】:How to capture only one line from a console process?如何从控制台进程中仅捕获一行?
【发布时间】:2013-05-10 05:22:27
【问题描述】:

我有一个应用程序启动,然后读取控制台进程的标准输出。在那个控制台进程中,我调用了一些写入控制台的 DLL 文件。但我不想捕获这些消息,我只想捕获它们发送的输出字符串。

我试过了:

verboseMethod(); //method writting things into the console

output = dllMethod(); //method returning what I want

Console.Clear();
Console.Out.Write(output)

我正在这样做,所以我相信我在 Console.Clear() 执行之前阅读了所有内容:

exeProcess.BeginOutputReadLine();
                string errString = exeProcess.StandardError.ReadToEnd();

你能给我一个替代方案吗?比如等到最后一个输出消息给出或类似的东西?

编辑

我相信这样的事情会有所帮助(如果存在的话)..我可以告诉控制台不要重定向输出或不要在某个点写任何东西,然后允许它再次在代码的其他地方写吗?喜欢:

Console.CloseBuffer();

Console.OpenBuffer();

【问题讨论】:

  • 您可以做的是将输出重定向到一个流,然后在您获得所需内容后停止从该流中读取(“捕获”)。

标签: c# console


【解决方案1】:

您应该尝试使用输出的异步重定向,并打开和关闭“EnableRaisingEvents”,这样您就只能在您想要的执行之间进行捕获。使用 BeginOutputReadLine() 和 CancelOutputRead() 开始/停止控制台读取。

        var myOutput = new StringBuilder();
        var myProcess = new Process();
        myProcess.StartInfo = new ProcessStartInfo(path, command);
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.RedirectStandardOutput = true;
        myProcess.StartInfo.RedirectStandardError = true;
        myProcess.EnableRaisingEvents = true;

        myProcess.OutputDataReceived += (object sendingProcess, DataReceivedEventArgs e) =>
        {
            if (e.Data != null)
            {
                myOutput.AppendLine(e.Data);
            }
        };

        myProcess.ErrorDataReceived += (object sendingProcess, DataReceivedEventArgs e) =>
        {
            if (e.Data != null)
            {
                myOutput.AppendLine(e.Data);
            }
        };
        myProcess.Start();

        verboseMethod();

        //Start Capture here!
        myProcess.BeginErrorReadLine();
        myProcess.BeginOutputReadLine();

        dllMethod();

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多