「Seriously? 在ASP.NET執行批次檔(batch file),為什麼你會想這麼做?」
我知道你會想這麼問,但是我只能用程式碼回答你:
「Seriously? 在ASP.NET執行批次檔(batch file),為什麼你會想這麼做?」
我知道你會想這麼問,但是我只能用程式碼回答你:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = @"D:\HelloWorld.bat";
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
System.IO.StreamReader StandardError = proc.StandardError;
System.IO.StreamReader StandardOutput = proc.StandardOutput;
System.IO.StreamWriter OutputLog = new System.IO.StreamWriter(@"D:\output.txt");
OutputLog.Write(StandardOutput.ReadToEnd());
StandardOutput.Close();
OutputLog.Close();
System.IO.StreamWriter ErrorLog = new System.IO.StreamWriter(@"D:\error.txt");
ErrorLog.Write(StandardError.ReadToEnd());
StandardError.Close();
ErrorLog.Close();
RedirectStandardOutput/Error如果沒有設為true,會因為權限問題發生錯誤。
另外如果你的批次檔會執行很長一段時間,就不要用ReadToEnd方法來讀取Ouput和Error,原因摘自MSDN如下:
ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.
換成三個字就是:會卡住。
參考資料: