[ASP.NET]呼叫DOS指令執行.EXE

  • 5589
  • 0
  • 2016-05-30

摘要:[ASP.NET]呼叫DOS指令執行.EXE

利用以下3種方式可順利在asp.net端執行.exe
1.在ProcessStartInfo物件裡指定.exe的名稱,然後執行

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;

startInfo.FileName = exeFileName;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;

Process.Start(startInfo);//非同步執行之後,不等待,程式繼續往下執行


2.在ProcessStartInfo物件裡指定.exe的名稱以及路徑以及參數,然後執行


Boolean blnResult = false; //預設執行失敗
//宣告指令內容 ProcessStartInfo
//他是用來放你要執行的DOS指令
System.Diagnostics.ProcessStartInfo psi =
  new System.Diagnostics.ProcessStartInfo(System.Windows.Forms.Application.StartupPath + "\\" + "getbinfile.exe");
psi.Arguments = filename + " " + filename.Replace("user", strDecrypUserFileName); //從user輸出轉成user_d.txt
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process prsFile; //用process去執行上面的command
prsFile = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = prsFile.StandardOutput;

//等待程式完成,最多等6秒            
for (int i = 1; i < 3; i++)
{
	if (!prsFile.HasExited)
	{
		prsFile.WaitForExit(2000);
	}
}
if (!prsFile.HasExited)
{
	this.Add_JobErrorLog(string.Format("執行{0}時發生錯誤", targetTable));
}
else
{
	blnResult = true;//執行成功
}
return blnResult;

3.另外透過呼叫cmd指令,再於cmd裡面去湊執行目標.exe的字串

var processStartInfo = new ProcessStartInfo();
processStartInfo.WorkingDirectory = "D:\\YourFolder";
processStartInfo.FileName = "cmd.exe";
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;

// set additional properties     
Process proc = Process.Start(processStartInfo);
proc.StandardInput.WriteLine("myExe.exe myargs1 myargs2 myargs3 ");
// add this line to prevent your asp.net code die in the console
proc.WaitForExit(5000);

但是常常有些.exe不支援第一種方式執行,這時候就要用第二種最土砲的方式,在command line 裡面去湊要執行的指令字串。

如果在本機asp.net測試都沒有問題,到了發佈到正式機的時候卻會失敗的時候,八成都是asp.net的執行權限不足,可以試著到
iis站台裡面去設定應用程式集區的權限,原本預設的執行user應該是ApplicationPoolIdentity(IIS7以上),這時候請跟你的系統管理員申請一個
有權限執行.exe的帳號,把這個應用程式集區執行user改成申請的帳號就可以了。