c# 执行命令并获取输出文本
1. 一次性全获取(适合快速命令)
void Main() { var result = Execute(@"ffmpeg.exe", "-h", 10); result.Dump(); } public string Execute(string filepath,string args, int seconds) { string output = ""; //输出字符串 if (args != null && !args.Equals("")) { using (var process = new Process())//创建进程对象 { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = filepath; //设定需要执行的命令 startInfo.Arguments = args; //“/C”表示执行完命令后马上退出 startInfo.UseShellExecute = false;//不使用系统外壳程序启动 startInfo.RedirectStandardInput = false;//不重定向输入 startInfo.RedirectStandardOutput = true; //重定向输出 startInfo.CreateNoWindow = true;//不创建窗口 process.StartInfo = startInfo; if (process.Start())//开始进程 { if (seconds == 0) process.WaitForExit();//这里无限等待进程结束 else process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒 output = process.StandardOutput.ReadToEnd();//读取进程的输出 } } } return output; }
2. 异步分批获取(适合长时间运行的任务,当然,要在此基础上加工一下,这只是基本原型)
void Main() { var result = string.Empty; Execute(@"ffmpeg.exe", "-h", out result); result.Dump(); } public void Execute(string filepath, string args, out string result) { using (var process = new Process()) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = filepath; startInfo.Arguments = args; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; process.StartInfo = startInfo; var sb = new StringBuilder(); DataReceivedEventHandler outputHandler = (s, e) => { if (e.Data != null) sb.AppendLine(e.Data); }; process.ErrorDataReceived += outputHandler; process.OutputDataReceived += outputHandler; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); result = sb.ToString(); } } // Define other methods and classes here
桂棹兮兰桨,击空明兮溯流光。