C# 读取批处理文件(.bat)执行结果到程序显示

时间:2022-09-02 23:57:09
        public static string ExcuteBatFile(string batPath, ref string errMsg)
        {
            if (errMsg == null) throw new ArgumentNullException("errMsg");
            string output;
            using (Process process = new Process())
            {
                FileInfo file = new FileInfo(batPath);
                if (file.Directory != null)
                {
                    process.StartInfo.WorkingDirectory = file.Directory.FullName;
                }
                process.StartInfo.FileName = batPath;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                process.WaitForExit();
                output = process.StandardOutput.ReadToEnd();
                errMsg = process.StandardError.ReadToEnd();
            }
            return output;
        }

使用方法:

var bat = System.Threading.Thread.GetDomain().BaseDirectory + "temp.bat";
string path = bat;
string errMsg = string.Empty;
string output = ExcuteBatFile(path, ref errMsg);