2011-05-04 14 views
6

我試圖通過ASP.Net頁面在服務器上運行批處理文件,這讓我瘋狂。當我運行下面的代碼時,沒有什麼令人滿意的 - 我可以從一些日誌語句看到這段代碼運行,但是我傳遞給該函數的.bat文件從不運行。從ASP.Net頁面運行批處理文件

有人能告訴我我做錯了什麼嗎?

public void ExecuteCommand(string batchFileLocation) 
{ 
    Process p = new Process(); 

    // Create secure password 
    string prePassword = "myadminpwd"; 
    SecureString passwordSecure = new SecureString(); 
    char[] passwordChars = prePassword.ToCharArray(); 
    foreach (char c in passwordChars) 
    { 
     passwordSecure.AppendChar(c); 
    } 

    // Set up the parameters to the process 
    p.StartInfo.FileName = @"C:\\Windows\\System32\cmd.exe"; 
    p.StartInfo.Arguments = @" /C " + batchFileLocation; 
    p.StartInfo.LoadUserProfile = true; 
    p.StartInfo.UserName = "admin"; 
    p.StartInfo.Password = passwordSecure; 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.CreateNoWindow = true; 

    // Run the process and wait for it to complete 
    p.Start(); 
    p.WaitForExit(); 
} 

在「應用程序」事件查看器登錄服務器,每次我嘗試運行這個時候,下面的問題似乎出現:

錯誤的應用程序CMD.EXE,版本6.0.6001.18000 ,時間戳0x47918bde,錯誤模塊kernel32.dll,版本6.0.6001.18000,時間戳0x4791a7a6,異常代碼0xc0000142,故障偏移量0x00009cac,進程ID 0x8bc,應用程序啓動時間0x01cc0a67825eda4b。

UPDATE

下面的代碼工作正常(它運行的批處理文件):

Process p = new Process(); 
p.StartInfo.FileName = batchFileLocation; 
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation); 
p.StartInfo.UseShellExecute = false; 

// Run the process and wait for it to complete 
p.Start(); 
p.WaitForExit(); 

然而,這並不(當我嘗試爲特定用戶身份運行):

Process p = new Process(); 

// Create secure password 
string prePassword = "adminpassword"; 
SecureString passwordSecure = new SecureString(); 
char[] passwordChars = prePassword.ToCharArray(); 
foreach (char c in passwordChars) 
{ 
     passwordSecure.AppendChar(c); 
} 

p.StartInfo.FileName = batchFileLocation; 
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.UserName = "admin"; 
p.StartInfo.Password = passwordSecure; 

// Run the process and wait for it to complete 
p.Start(); 
p.WaitForExit(); 

回答

1

一點谷歌的「錯誤的應用程序的cmd.exe」,點我到這個IIS forum

看來你不能在IIS的後臺創建一個新的進程,除非你使用CreateProcessWithLogon方法。 (我沒有測試過)。

+0

這看起來像我看到的問題沒關係 - 不幸的是,從IIS論壇主題到解決方案的鏈接似乎已經停止。 – 2011-05-04 15:43:23

4

只需直接調用批處理文件:

p.StartInfo.FileName = batchFileLocation; 

此外,確保WorkingDirectory設置到正確的位置:

p.StartInfo.WorkingDirectory= Path.GetDirectoryName(batchFileLocation); 
+0

我已經試過這個,我得到了同樣的結果。代碼似乎運行正常,但批處理文件從不啓動。 – 2011-05-04 14:34:53

+0

@Jimmy - 你檢查了傳入的參數嗎?它是否正確並且文件位於傳入的位置? – Oded 2011-05-04 14:36:28

+0

是的我已經把參數放到一個日誌文件來檢查它是否正常,並檢查實際文件是否存在。 – 2011-05-04 14:37:20