Capturing console output from a .NET application (C#)

后端 未结 8 2294
臣服心动
臣服心动 2020-11-22 02:20

How do I invoke a console application from my .NET application and capture all the output generated in the console?

(Remember, I don\'t want to save the information

8条回答
  •  星月不相逢
    2020-11-22 02:51

    ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.

    The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.

    Also available as NuGet package.

    Sample call to get full console output:

    // Run simplest shell command and return its output.
    public static string GetWindowsVersion()
    {
        return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
    }
    

    Sample with live feedback:

    // Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
    public static void PingUrl(string url, Action replyHandler)
    {
        var regex = new Regex("(time=|Average = )(?

提交回复
热议问题