.net 程式碼呼叫cmd執行.exe程式,獲取控制檯輸出資訊
阿新 • • 發佈:2018-11-07
使用.net core 對老專案升級, .net core 使用TripleDES.Create() 加密眾iv位元組限制 與 framework中的不同, 新專案還需要相容老專案版本,還不想通過webapi 進行資料request和response, 遂想到使用控制檯輸出的形式進行嘗試, 具體程式碼如下;
.net core
private static readonly string CmdPath = @"C:\Windows\System32\cmd.exe"; /// <summary> /// 執行cmd命令/// 多命令請使用批處理命令連線符: /// <![CDATA[ /// &:同時執行兩個命令 /// |:將上一個命令的輸出,作為下一個命令的輸入 /// &&:當&&前的命令成功時,才執行&&後的命令 /// ||:當||前的命令失敗時,才執行||後的命令]]> /// 其他請百度 /// </summary> /// <param name="cmd"></param> /// <param name="output"></param>private static string RunCmd(string cmd) { string param = $"{Environment.CurrentDirectory}//xxx.exe {cmd} &exit";//說明:不管命令是否成功均執行exit命令,否則當呼叫ReadToEnd()方法時,會處於假死狀態 string result = string.Empty; using (Process p = new Process()) { p.StartInfo.FileName= CmdPath; p.StartInfo.UseShellExecute = false; //是否使用作業系統shell啟動 p.StartInfo.RedirectStandardInput = true; //接受來自呼叫程式的輸入資訊 p.StartInfo.RedirectStandardOutput = true; //由呼叫程式獲取輸出資訊 p.StartInfo.RedirectStandardError = true; //重定向標準錯誤輸出 p.StartInfo.CreateNoWindow = true; //不顯示程式視窗 p.Start();//啟動程式 //向cmd視窗寫入命令 p.StandardInput.WriteLine(param); p.StandardInput.AutoFlush = true; //獲取cmd視窗的輸出資訊 result = p.StandardOutput.ReadToEnd(); if (!string.IsNullOrEmpty(result)) result = result.Substring(result.LastIndexOf("&exit") + 5, result.Length - result.LastIndexOf("&exit") - 5).Trim(); p.WaitForExit();//等待程式執行完退出程序 p.Close(); } return result; }
exe 控制檯程式碼
static void Main(string[] args) { if (args.Length <= 0) { Environment.Exit(0); } else { string[] _param = args; string _type = _param[0]; string res = string.Empty; switch (_type) { case "RefreshToken": res = Identity.instance.RefreshToken(_param[1], _param[2]); break; } Console.Out.WriteLine(res); Console.Out.Close(); } }
注: 在使用的過程中,需要注意exe的存放位置, 和呼叫時候載入的地址對應,