C#中执行Linux命令并且拿到返回值
很多应用场景,比如说获取linux系统中某个文件大小,文件内容,只要能从控制台打印的命令便可以使用此方法
1 try 2 { 3 4 var str = $"执行的命令"; 5 Process p = new Process(); 6 //设置要启动的应用程序 7 p.StartInfo.FileName = "bash"; 8 //是否使用操作系统shell启动 9 p.StartInfo.UseShellExecute = false; 10 // 接受来自调用程序的输入信息 11 p.StartInfo.RedirectStandardInput = true; 12 //输出信息 13 p.StartInfo.RedirectStandardOutput = true; 14 // 输出错误 15 p.StartInfo.RedirectStandardError = false; 16 //不显示程序窗口 17 p.StartInfo.CreateNoWindow = true; 18 p.Start(); 19 p.StandardInput.WriteLine(str); 20 p.StandardInput.Close(); 21 var fileData = p.StandardOutput.ReadToEnd(); 22 p.WaitForExit(); 23 p.Close(); 24 _logger.LogDebug($"查看命令返回数据{fileData} {str}"); 25 26 27 } 28 catch (Exception e) 29 { 30 _logger.LogDebug($"{e.Message}"); 31 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界