还有一种将所有输出作为事件获取的另一种方法,当它们被另一个控制台应用程序
cmd_DataReceived输出时,每当有输出时就引发该事件,而在另一个应用程序中
cmd_Error出现错误时则引发所有事件。
如果要解析输出,则处理这些事件可能是读取输出并在发生错误时在其他应用程序中处理错误的更好方法。
using System;using System.Diagnostics;namespace InteractWithConsoleApp{ class Program { static void Main(string[] args) { ProcessStartInfo cmdStartInfo = new ProcessStartInfo(); cmdStartInfo.FileName = @"C:WindowsSystem32cmd.exe"; cmdStartInfo.RedirectStandardOutput = true; cmdStartInfo.RedirectStandardError = true; cmdStartInfo.RedirectStandardInput = true; cmdStartInfo.UseShellExecute = false; cmdStartInfo.CreateNoWindow = true; Process cmdProcess = new Process(); cmdProcess.StartInfo = cmdStartInfo; cmdProcess.ErrorDataReceived += cmd_Error; cmdProcess.OutputDataReceived += cmd_DataReceived; cmdProcess.EnableRaisingEvents = true; cmdProcess.Start(); cmdProcess.BeginOutputReadLine(); cmdProcess.BeginErrorReadLine(); cmdProcess.StandardInput.WriteLine("ping www.bing.com"); //Execute ping bing.com cmdProcess.StandardInput.WriteLine("exit"); //Execute exit. cmdProcess.WaitForExit(); } static void cmd_DataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Output from other process"); Console.WriteLine(e.Data); } static void cmd_Error(object sender, DataReceivedEventArgs e) { Console.WriteLine("Error from other process"); Console.WriteLine(e.Data); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)