.net 执行cmd脚本

最近根据项目去球,需要使用.net core去执行脚本,,使用npm安装模块,于是就整理了下代码,如下:

        /// <summary>
        /// 安装应用app
        /// </summary>
        /// <param name="companyID">公司code</param>
        /// <param name="appName">应用模块名称</param>
        /// <returns></returns>
        public ReturnEntity installApp(string companyCode, string appName)
        {
            ReturnEntity ret = new ReturnEntity();
            Process process = new Process();
            try
            {
                // 定位脚本执行目录,
                // 不设置,则默认为程序运行目录
                string basePath = Directory.GetCurrentDirectory();
                string dir = basePath + $"/wwwroot/src/@{companyCode}/{appName}";
                process.StartInfo.WorkingDirectory = dir;
                process.StartInfo.UseShellExecute = false;   //是否使用操作系统shell启动 
                process.StartInfo.CreateNoWindow = true;   //是否在新窗口中启动该进程的值 (不显示程序窗口)
                process.StartInfo.RedirectStandardInput = true;  // 接受来自调用程序的输入信息 
                process.StartInfo.RedirectStandardOutput = true;  // 由调用程序获取输出信息
                process.StartInfo.RedirectStandardError = true;  //重定向标准错误输出
                process.StartInfo.FileName = "cmd.exe";
                process.Start();                         // 启动程序
                // 测试命令
                //process.StandardInput.WriteLine("help"); //向cmd窗口发送输入信息
                process.StandardInput.AutoFlush = true;
                // 前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
                process.StandardInput.WriteLine("exit");

                StreamReader reader = process.StandardOutput;//获取exe处理之后的输出信息
                string curLine = reader.ReadLine(); //获取错误信息到error
                while (!reader.EndOfStream)
                {
                    if (!string.IsNullOrEmpty(curLine))
                    {
                        Console.WriteLine(curLine);
                    }
                    curLine += reader.ReadLine();
                }

                // 返回执行结果
                ret.msg = curLine;
                reader.Close(); //close进程

                process.WaitForExit();  //等待程序执行完退出进程
                process.Close();
            }
            catch (Exception e)
            {
                ret.code = -1;
                ret.msg = "500 error,please view system error log!";// + ex.Message;
                MyLib.LogUtil.Error(e);
            }
            return ret;
        }
posted @   亘古不变  阅读(3)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示