Process.start: how to get the output?

后端 未结 9 1367
無奈伤痛
無奈伤痛 2020-11-21 23:56

I would like to run an external command line program from my Mono/.NET app. For example, I would like to run mencoder. Is it possible:

  1. To get
相关标签:
9条回答
  • 2020-11-22 00:59

    When you create your Process object set StartInfo appropriately:

    var proc = new Process 
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "program.exe",
            Arguments = "command line arguments to your executable",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        }
    };
    

    then start the process and read from it:

    proc.Start();
    while (!proc.StandardOutput.EndOfStream)
    {
        string line = proc.StandardOutput.ReadLine();
        // do something with line
    }
    

    You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

    0 讨论(0)
  • 2020-11-22 00:59

    Alright, for anyone who wants both Errors and Outputs read, but gets deadlocks with any of the solutions, provided in other answers (like me), here is a solution that I built after reading MSDN explanation for StandardOutput property.

    Answer is based on T30's code:

    static void runCommand()
    {
        //* Create your Process
        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c DIR";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        //* Set ONLY ONE handler here.
        process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
        //* Start process
        process.Start();
        //* Read one element asynchronously
        process.BeginErrorReadLine();
        //* Read the other one synchronously
        string output = process.StandardOutput.ReadToEnd();
        Console.WriteLine(output);
        process.WaitForExit();
    }
    
    static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
    {
        //* Do your stuff with the output (write to console/log/StringBuilder)
        Console.WriteLine(outLine.Data);
    }
    
    0 讨论(0)
  • 2020-11-22 00:59
    1. It is possible to get the command line shell output of a process as described here : http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx

    2. This depends on mencoder. If it ouputs this status on the command line then yes :)

    0 讨论(0)
提交回复
热议问题