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

后端 未结 8 2432
臣服心动
臣服心动 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: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 onStdOut = null,
                           Action 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 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); } 
    );
    

提交回复
热议问题