C# Process获取重定向输出

By | 2017年11月21日

在调用外部程序时,可以直接获取输出内容,在C#代码中处理。

收集了两种方式,传统的和异步的。

//传统方式:
public static void RunExe(string exePath, string arguments, out string output, out string error)
{
	using (Process process = new System.Diagnostics.Process())
	{
		process.StartInfo.FileName = exePath;
		process.StartInfo.Arguments = arguments;
		// 必须禁用操作系统外壳程序    
		process.StartInfo.UseShellExecute = false;
		process.StartInfo.CreateNoWindow = true;
		process.StartInfo.RedirectStandardOutput = true;
		process.StartInfo.RedirectStandardError = true;

		process.Start();

		output = process.StandardOutput.ReadToEnd();
		error = process.StandardError.ReadToEnd();

		process.WaitForExit();
		process.Close();
	}
}

异步方式:

 //异步方式
 public static void ExecuteCommand(string command,string arguments, out string output, out string error)
 {
     try
     {
         //创建一个进程  
         Process process = new Process();
         process.StartInfo.FileName = command;
         process.StartInfo.Arguments = arguments;

         // 必须禁用操作系统外壳程序  
         process.StartInfo.UseShellExecute = false;
         process.StartInfo.CreateNoWindow = true;
         process.StartInfo.RedirectStandardOutput = true;
         process.StartInfo.RedirectStandardError = true;


         //启动进程  
         process.Start();

         //准备读出输出流和错误流  
         string outputData = string.Empty;
         string errorData = string.Empty;
         process.BeginOutputReadLine();
         process.BeginErrorReadLine();

         process.OutputDataReceived += (sender, e) =>
         {
             outputData += (e.Data + "\n");
         };

         process.ErrorDataReceived += (sender, e) =>
         {
             errorData += (e.Data + "\n");
         };

         //等待退出  
         process.WaitForExit();

         //关闭进程  
         process.Close();

         //返回流结果  
         output = outputData;
         error = errorData;
     }
     catch (Exception)
     {
         output = null;
         error = null;
     }
 }