[轉貼] asp.net 執行Server上的EXE執行檔

 

 **********************************************************************************

asp.net_執行Server上的EXE執行檔

依照前篇的敘述,第二個要處理的問題是,如何利用asp.net呼叫Server上的exe執行。


如果查網路資料,會查到很多一模一樣的文章,基本上有兩種方式:


1. 利用ShellExecute來處理。

引用:


using System.Runtime.InteropServices;


宣告:


[DllImport("shell32.dll")]

private static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, Int32 nShowCmd);


程式碼:


string Dir = page.Server.MapPath("~/");

string CmdStr = Dir + "geoidint.exe";

ShellExecute(IntPtr.Zero, "open", CmdStr, "-I" + Dir + "input.txt -G" + Dir + "output.txt", null, 1);


比較需要注意的地方是,如果你跟我一樣需要傳入參數,就在ShellExecute的第四個參數傳入;又如果傳入的參數是檔案路徑,就要看你所執行的EXE檔是怎麼抓的,像我必須傳入完整路徑,所以參數的部分採組合字串的方式。


2. 利用System.Diagnostics.Process來處理。

引用:


using System.Diagnostics;


程式碼:


Process process = new Process();

process.StartInfo.FileName = Dir + "geoidint.exe";

process.StartInfo.Arguments = "-I" + Dir + "input.txt -G" + Dir + "output.txt";

process.StartInfo.UseShellExecute = false;

process.StartInfo.RedirectStandardError = true;

process.StartInfo.RedirectStandardOutput = true;

process.StartInfo.RedirectStandardInput = true;

process.StartInfo.CreateNoWindow = false;

process.Start();

if (!process.WaitForExit(1000*15))

{

process.Kill();

}


也是一樣注意傳入參數的部份,如果是檔案位置,請確認路徑是否正確。而在我的規劃中,我必須等待呼叫的執行檔將輸出檔產出後,才讀取新產出的輸出檔內容,再回傳到頁面上,所以另外一個需要注意的地方是最後的判斷式process.WaitForExit(1000*15),用處是:在process完成或15秒後往下執行,如果15秒還未執行完,則殺掉這個執行緒。


*在測試的時候,建議先在本機測試,可以正確執行後,在移至伺服器上。以確認出錯時到底是程式問題還是aspnet的權限問題。若權限問題,則將aspnet帳號加入EXE所在資料夾。


***********************************************************************************

目的: 呼叫本機端 C:\PE_Excel\PE_Excel.exe 程式, 有兩種方法可以參考


第一: 利用同步模式, 也就是說, 一定要先執行完該程(PE_Excel.exe)式之後, 才能繼續其他的程式


            System.Diagnostics.Process os = new System.Diagnostics.Process();

            os.StartInfo.FileName = @"C:\PE_Excel\PE_Excel.exe";

            os.Start();

            os.WaitForExit();

            os.Close();


第二: 非同步模式, 也就是說, 不用等待該程式(PE_Excel.exe)執行完畢, 即繼續執行其他程式


  Process.Start(@"C:\PE_Excel\PE_Excel.exe");

留言

這個網誌中的熱門文章

TeknoParrot 模擬器介紹,俗稱《鸚鵡模擬器》

[轉貼] ASP.NET傳遞參數給Crystal Report做Export或Print的動作

[轉貼] Server 端Post資料到 .ashx