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

后端 未结 17 1230
既然无缘
既然无缘 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:46
     System.Diagnostics.ProcessStartInfo psi =
       new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
     psi.RedirectStandardOutput = true;
     psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
     psi.UseShellExecute = false;
     System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
     System.IO.StreamReader myOutput = proc.StandardOutput;
     proc.WaitForExit(2000);
     if (proc.HasExited)
      {
          string output = myOutput.ReadToEnd();
     }
    
    0 讨论(0)
  • 2020-11-21 13:47
    // 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 = "YOURBATCHFILE.bat";
     p.Start();
     // Do not wait for the child process to exit before
     // reading to the end of its redirected stream.
     // p.WaitForExit();
     // Read the output stream first and then wait.
     string output = p.StandardOutput.ReadToEnd();
     p.WaitForExit();
    

    Code is from MSDN.

    0 讨论(0)
  • 2020-11-21 13:48

    There one other parameter I found useful, which I use to eliminate the process window

    pProcess.StartInfo.CreateNoWindow = true;
    

    this helps to hide the black console window from user completely, if that is what you desire.

    0 讨论(0)
  • 2020-11-21 13:50

    There is a ProcessHelper Class in PublicDomain open source code which might interest you.

    0 讨论(0)
  • 2020-11-21 13:51
    // usage
    const string ToolFileName = "example.exe";
    string output = RunExternalExe(ToolFileName);
    
    public string RunExternalExe(string filename, string arguments = null)
    {
        var process = new Process();
    
        process.StartInfo.FileName = filename;
        if (!string.IsNullOrEmpty(arguments))
        {
            process.StartInfo.Arguments = arguments;
        }
    
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo.UseShellExecute = false;
    
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardOutput = true;
        var stdOutput = new StringBuilder();
        process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.
    
        string stdError = null;
        try
        {
            process.Start();
            process.BeginOutputReadLine();
            stdError = process.StandardError.ReadToEnd();
            process.WaitForExit();
        }
        catch (Exception e)
        {
            throw new Exception("OS error while executing " + Format(filename, arguments)+ ": " + e.Message, e);
        }
    
        if (process.ExitCode == 0)
        {
            return stdOutput.ToString();
        }
        else
        {
            var message = new StringBuilder();
    
            if (!string.IsNullOrEmpty(stdError))
            {
                message.AppendLine(stdError);
            }
    
            if (stdOutput.Length != 0)
            {
                message.AppendLine("Std output:");
                message.AppendLine(stdOutput.ToString());
            }
    
            throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message);
        }
    }
    
    private string Format(string filename, string arguments)
    {
        return "'" + filename + 
            ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) +
            "'";
    }
    
    0 讨论(0)
  • 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:

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