如何:在C#中执行命令行,获得STD OUT结果

如何从C#执行命令行程序并取回STD OUT结果。 具体来说,我想执行两个文件编程方式selectDIFF并将结果写入文本框。 是的,我可以为自己弄清楚,但肯定有人做了这样的事情,我很懒。

// 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(); 

代码来自MSDN 。

这是一个快速示例:

 //Create process System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); //strCommand is path and file name of command to run pProcess.StartInfo.FileName = strCommand; //strCommandParameters are parameters to pass to program pProcess.StartInfo.Arguments = strCommandParameters; pProcess.StartInfo.UseShellExecute = false; //Set output of program to be written to process output stream pProcess.StartInfo.RedirectStandardOutput = true; //Optional pProcess.StartInfo.WorkingDirectory = strWorkingDirectory; //Start the process pProcess.Start(); //Get program output string strOutput = pProcess.StandardOutput.ReadToEnd(); //Wait for process to finish pProcess.WaitForExit(); 

还有一个其他的参数我觉得很有用,我用它来消除这个过程窗口

 pProcess.StartInfo.CreateNoWindow = true; 

这有助于完全隐藏用户的黑色控制台窗口,如果这是你的愿望。

 // 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) + "'"; } 
  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(); } 

您将需要使用启用了RedirectStandardOutput ProcessStartInfo – 然后您可以读取输出stream。 您可能会发现使用“>”将输出redirect到文件(通过操作系统)更容易,然后只需读取该文件即可。

[编辑:就像雷做的那样:+1]

这可能不是最好的/最简单的方法,但可能是一个select:

从代码执行时,添加“> output.txt”,然后读取output.txt文件。

您可以使用Process类启动任何命令行程序,并使用您创build的stream读取器(基于string或内存位置)设置Process实例的StandardOutput属性。 过程完成后,你可以做任何你需要在该stream的差异。

在PublicDomain开放源代码中有一个ProcessHelper类可能会让你感兴趣。

如果您试图查询PC / Server上的本地ARPcaching,这可能对某人有用。

 List<string[]> results = new List<string[]>(); using (Process p = new Process()) { p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.Arguments = "/c arp -a"; p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe"; p.Start(); string line; while ((line = p.StandardOutput.ReadLine()) != null) { if (line != "" && !line.Contains("Interface") && !line.Contains("Physical Address")) { var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray(); var arrResult = new string[] { lineArr[0], lineArr[1], lineArr[2] }; results.Add(arrResult); } } p.WaitForExit(); } 

如果您不介意引入依赖项, CliWrap可以为您简化这一点:

 var cli = new Cli("target.exe"); var output = await cli.ExecuteAsync("arguments", "stdin"); var stdout = output.StandardOutput;