zoukankan      html  css  js  c++  java
  • Process.start: how to get the output?

    1: Synchronous example

    static void runCommand() {
        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
        //* Read the output (or the error)
        string output = process.StandardOutput.ReadToEnd();
        Console.WriteLine(output);
        string err = process.StandardError.ReadToEnd();
        Console.WriteLine(err);
        process.WaitForExit();
    }

    Note that it's better to process both output and errors: they must be handled separately.

    (*) For some commands (here StartInfo.Arguments) you must add the /c directive, otherwise the process freezes in the WaitForExit().

    2: Asynchronous example

    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 your output and error (asynchronous) handlers
        process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
        process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
        //* Start process and handlers
        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit();
    }
    static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
        //* Do your stuff with the output (write to console/log/StringBuilder)
        Console.WriteLine(outLine.Data);
    }

    If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:

    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
    process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
  • 相关阅读:
    《JavaScript》forEach()和map()
    《JavaScript》split和join
    09慕课网《进击Node.js基础(一)》HTTP-get/request
    08慕课网《进击Node.js基础(一)》事件events
    07慕课网《进击Node.js基础(一)》HTTP小爬虫
    06慕课网《进击Node.js基础(一)》作用域和上下文
    05慕课网《进击Node.js基础(一)》HTTP概念进阶(同步/异步)
    前端每周学习分享--第4期
    前端每周学习分享--第3期
    前端每周学习分享--第2期
  • 原文地址:https://www.cnblogs.com/zeroone/p/4709335.html
Copyright © 2011-2022 走看看