How To: Execute command line in C#, get STD OUT results

后端 未结 17 1247
既然无缘
既然无缘 2020-11-21 13:12

How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and wr

17条回答
  •  天涯浪人
    2020-11-21 13:53

    In case you also need to execute some command in the cmd.exe, you can do the following:

    // Start the child process.
    Process p = new Process();
    // Redirect the output stream of the child process.
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.Arguments = "/C vol";
    p.Start();
    // Read the output stream first and then wait.
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    Console.WriteLine(output);
    

    This returns just the output of the command itself:

    You can also use StandardInput instead of StartInfo.Arguments:

    // Start the child process.
    Process p = new Process();
    // Redirect the output stream of the child process.
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "cmd.exe";
    p.Start();
    // Read the output stream first and then wait.
    p.StandardInput.WriteLine("vol");
    p.StandardInput.WriteLine("exit");
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    Console.WriteLine(output);
    

    The result looks like this:

提交回复
热议问题