我们可以使有dotnetcore跨平台的特性,优雅的实现在dotnetcore执行shell (bash). 代码如下: using System;using System.Collections.Generic;using System.Text;namespace hshoc{ using System.Diagnostics; public static class ShellHelper { public static string Bash(this string cmd) { var escapedArgs = cmd.Replace("\"", "\\\""); var process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = $"-c \"{escapedArgs}\"", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, } }; process.Start(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } } } 为什么使用dotnetcore, 其性能比java更好,使用C#的扩展方法, 具体调用上面的代码是 var output = "ps aux".Bash(); 是不是比较方便。大家可以延伸自动的应用。我们编写更复杂的SHELL脚本在其中,充分利用c#的特性,快速开发,易于调试。 |
|