How to parse command line output from c#?

后端 未结 1 509
你的背包
你的背包 2020-11-27 14:18

I want to execute an application(command line application) from the C#... and I want after executing this application and providing the input to it, I want to parse the outp

相关标签:
1条回答
  • 2020-11-27 14:37

    There is one more way of getting all the output as events as and when they are output by the other console application cmd_DataReceived gets raised whenever there is output and cmd_Error gets raised whenever there is an error raised in the other application.

    If you want to parse the output, probably handling these events is a better way to read output and handle errors in the other application as and when they occur.

    using System;
    using System.Diagnostics;
    
    namespace InteractWithConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
                cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                cmdStartInfo.RedirectStandardOutput = true;
                cmdStartInfo.RedirectStandardError = true;
                cmdStartInfo.RedirectStandardInput = true;
                cmdStartInfo.UseShellExecute = false;
                cmdStartInfo.CreateNoWindow = true;
    
                Process cmdProcess = new Process();
                cmdProcess.StartInfo = cmdStartInfo;
                cmdProcess.ErrorDataReceived += cmd_Error;
                cmdProcess.OutputDataReceived += cmd_DataReceived;
                cmdProcess.EnableRaisingEvents = true;
                cmdProcess.Start();
                cmdProcess.BeginOutputReadLine();
                cmdProcess.BeginErrorReadLine();
    
                cmdProcess.StandardInput.WriteLine("ping www.bing.com");     //Execute ping bing.com
                cmdProcess.StandardInput.WriteLine("exit");                  //Execute exit.
    
                cmdProcess.WaitForExit();
            }
    
            static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
            {
                Console.WriteLine("Output from other process");
                Console.WriteLine(e.Data);
            }
    
            static void cmd_Error(object sender, DataReceivedEventArgs e)
            {
                Console.WriteLine("Error from other process");
                Console.WriteLine(e.Data);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题