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

后端 未结 8 2286
臣服心动
臣服心动 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 03:07

    Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.

    Then you can use Process.StandardOutput to read the program output.

    The second link has a sample code how to do it.

    0 讨论(0)
  • 2020-11-22 03:11

    I made a reactive version that accepts callbacks for stdOut and StdErr.
    onStdOut and onStdErr are called asynchronously,
    as soon as data arrives (before the process exits).

    public static Int32 RunProcess(String path,
                                   String args,
                           Action<String> onStdOut = null,
                           Action<String> onStdErr = null)
        {
            var readStdOut = onStdOut != null;
            var readStdErr = onStdErr != null;
    
            var process = new Process
            {
                StartInfo =
                {
                    FileName = path,
                    Arguments = args,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = readStdOut,
                    RedirectStandardError = readStdErr,
                }
            };
    
            process.Start();
    
            if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));
            if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));
    
            process.WaitForExit();
    
            return process.ExitCode;
        }
    
        private static void ReadStream(TextReader textReader, Action<String> callback)
        {
            while (true)
            {
                var line = textReader.ReadLine();
                if (line == null)
                    break;
    
                callback(line);
            }
        }
    


    Example usage

    The following will run executable with args and print

    • stdOut in white
    • stdErr in red

    to the console.

    RunProcess(
        executable,
        args,
        s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },
        s => { Console.ForegroundColor = ConsoleColor.Red;   Console.WriteLine(s); } 
    );
    
    0 讨论(0)
提交回复
热议问题