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

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

    This is bit improvement over accepted answer from @mdb. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because ReadToEnd() doesn't work if you want to capture both error and regular output. It took me while to make this work because it actually also requires BeginxxxReadLine() calls after Start().

    Asynchronous way:

    using System.Diagnostics;
    
    Process process = new Process();
    
    void LaunchProcess()
    {
        process.EnableRaisingEvents = true;
        process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
        process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);
        process.Exited += new System.EventHandler(process_Exited);
    
        process.StartInfo.FileName = "some.exe";
        process.StartInfo.Arguments = "param1 param2";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardOutput = true;
    
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();          
    
        //below line is optional if we want a blocking call
        //process.WaitForExit();
    }
    
    void process_Exited(object sender, EventArgs e)
    {
        Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString()));
    }
    
    void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data + "\n");
    }
    
    void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data + "\n");
    }
    

提交回复
热议问题