Linux系统执行命令方法-
时间:2022-05-25 作者:zsl817
现在我们无论是工作中还是学习中很多情况下用到Linux系统,当我们需要在C#代码中调用类似与cmd窗口执行命令时候,就需要用到此方法
public static Process CommitCommand(string commandStr, string workingDir, Action<DataReceivedEventArgs> action) { var logger = 域名urrentClassLogger(); try { 域名g("Get into CommitCommand"); Process process = new Process(); 域名Name = 域名tring(0, 域名xOf(" ")).Trim(); var pathDir = 域名nvironmentVariable("PATH").Split(域名Platform(域名x) ? ":" : ";", 域名veEmptyEntries) .FirstOrDefault(s => 域名ts(域名ine(s, 域名Name)) || 域名ts(域名ine(s, 域名Name + ".exe"))); if (域名llOrEmpty(pathDir)) { 域名Name = 域名ullPath(域名Name, workingDir); } 域名ments = 域名tring(域名xOf(" ")).Trim(); 域名ingDirectory = 域名llOrWhiteSpace(workingDir) ? 域名ingDirectory : workingDir; 域名teNoWindow = true; 域名rDialog = false; 域名hellExecute = false; 域名rectStandardOutput = true; 域名rectStandardError = true; 域名rectStandardInput = true; 域名rDataReceived += (sender, args) => { action(args); 域名r($"ErrorDataReceived:commandStr:{commandStr}. workingDir:{workingDir}. Error:{域名}"); }; 域名leRaisingEvents = true; 域名utDataReceived += (sender, args) => { action(args); //域名g($"OutputDataReceived:{域名}"); }; 域名ed += (sender, args) => { 域名g("程序退出!"); 域名r($"Exited:commandStr:{commandStr}. workingDir:{workingDir}"); }; 域名t(); 域名Flush = true;//域名eLine("") 域名nErrorReadLine(); 域名nOutputReadLine(); 域名g("Sign out CommitCommand"); return process; } catch (Exception e) { 域名r(e, "process can not start."); 域名g(域名age); return null; } }
调用也非常简单,参数1:执行得命令 参数2:路径 比如说我们需要运行mysql,就需要在对应文件夹内执行对应命令,这个时候第二个参数就可以传入路径
然后我再给出一个调用得例子
Process pc = new Process(); pc = 域名itCommand("nvidia-smi", "/", args => { if (!域名llOrEmpty(域名)) { 域名(域名); } }); 域名ForExit(); 域名ose();
我这里时查看显卡也就是GPU得信息的命令,可以再root下执行,然后我这里就传入了一个/,拿到执行命令返回的数据