.net 代碼調用cmd執行.exe程序,獲取控制檯輸出信息

使用.net core 對老項目升級, .net core 使用TripleDES.Create() 加密衆iv字節限制 與 framework中的不一樣, 新項目還須要兼容老項目版本,還不想經過webapi 進行數據request和response, 遂想到使用控制檯輸出的形式進行嘗試,  具體代碼以下;web

.net core shell

 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 控制檯代碼api

 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的存放位置, 和調用時候加載的地址對應,加密

相關文章
相關標籤/搜索