C#呼叫批處理(bat)檔案,並獲取執行批處理(bat)檔案後返回值
阿新 • • 發佈:2019-01-24
/// /// 執行BAT檔案 /// /// csv檔案引數 /// bat檔案執行返回值 static string execBAT(string fileName) { ProcessStartInfo pro = new System.Diagnostics.ProcessStartInfo("cmd.exe"); pro.UseShellExecute = false; pro.RedirectStandardOutput = true; pro.RedirectStandardError = true; pro.CreateNoWindow = true; pro.FileName = ConfigurationManager.AppSettings["BatFilePath"]; pro.Arguments = fileName; //pro.WorkingDirectory = System.Environment.CurrentDirectory; System.Diagnostics.Process proc = System.Diagnostics.Process.Start(pro); System.IO.StreamReader sOut = proc.StandardOutput; proc.Close(); string results = sOut.ReadToEnd().Trim(); //回顯內容 sOut.Close(); string[] values = results.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); return values[values.Length - 1]; } //另外一種獲取方式,在bat中設定exit code static string execBAT(string fileName) { ProcessStartInfo pro = new System.Diagnostics.ProcessStartInfo("cmd.exe"); pro.UseShellExecute = false; pro.RedirectStandardOutput = true; pro.RedirectStandardError = true; pro.CreateNoWindow = true; pro.FileName = ConfigurationManager.AppSettings["BatFilePath"]; pro.Arguments = fileName; //pro.WorkingDirectory = System.Environment.CurrentDirectory; System.Diagnostics.Process proc = System.Diagnostics.Process.Start(pro); proc.WaitForExit(); return proc.ExitCode.ToString(); }