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

后端 未结 8 2292
臣服心动
臣服心动 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:57

    Added process.StartInfo.**CreateNoWindow** = true; and timeout.

    private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
    {
        using (Process process = new Process())
        {
            process.StartInfo.FileName = exeName;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
    
            output = process.StandardOutput.ReadToEnd();
    
            bool exited = process.WaitForExit(timeoutMilliseconds);
            if (exited)
            {
                exitCode = process.ExitCode;
            }
            else
            {
                exitCode = -1;
            }
        }
    }
    

提交回复
热议问题