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
桂棹兮兰桨,击空明兮溯流光。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2023-01-12 java 定时器的使用
2023-01-12 跨进程同步锁的实现方法:
2023-01-12 java 通过 nmap 跨进程内存共享