ASP.NET 應用需在伺服器端調用 C++ 組件修改目標檔案,直接使用 Process 類啟動外部程式卻持續拋出「唯讀」錯誤。查閱資料多言 .NET 不允許此類操作,曾陷入僵局。
回憶經典 ASP 時代,WScript.Shell 可輕鬆執行外部命令並修改檔案。實測 ASP 頁面中使用該 COM 物件竟無報錯,遂尋找將其轉為 .NET 可用組件的方法。
%windir%\system32\WSHom.Ocx (即 WScript.Shell)。Tlbimp.exe WSHom.Ocx /out:WSHomx.dll
WSHomx.dll 放入 Web 專案 bin 目錄。無需註冊,即可直接引用,避免管理員誤刪風險。public void Receive()
{
string request = RequestHelper.RequestGetValue("fileName");
// 使用轉換後的 WSHomx.dll 中的 WshShell 類別
WshShell Cmd = new WshShell();
string result = Cmd.Exec(VoiceTestPath + " " + VoiceOutputPath + request + ".wav 2").StdOut.ReadAll();
HttpHelper.ResponseWrite(result);
// 原 Process 方式 (失敗) 保留參考
/*
if (!string.IsNullOrEmpty(request))
{
HttpHelper.ResponseWrite(ExecuteByProcess(VoiceTestPath, VoiceOutputPath + request + ".wav 2"));
}
*/
}
///
/// 原嘗試用 Process 啟動外部程式 (權限受限)
///
private static string ExecuteByProcess(string CommandPath, string Arguments)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = CommandPath;
p.StartInfo.Arguments = Arguments;
return StartProcess(p, 500);
}
private static string StartProcess(Process p, int milliseconds)
{
string output = "";
try
{
if (p.Start())
{
if (milliseconds == 0) p.WaitForExit();
else p.WaitForExit(milliseconds);
output = p.StandardOutput.ReadToEnd();
}
}
catch { }
finally { if (p != null) p.Close(); }
return output;
}
此法同樣適用於其他需伺服器端執行外部命令的場景,解決權限困擾。