首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

解決 .NET 服務端調用 C++ 組件修改檔案的權限問題

     編輯:關於.NET

問題背景

ASP.NET 應用需在伺服器端調用 C++ 組件修改目標檔案,直接使用 Process 類啟動外部程式卻持續拋出「唯讀」錯誤。查閱資料多言 .NET 不允許此類操作,曾陷入僵局。

靈感來源:WScript.Shell

回憶經典 ASP 時代,WScript.Shell 可輕鬆執行外部命令並修改檔案。實測 ASP 頁面中使用該 COM 物件竟無報錯,遂尋找將其轉為 .NET 可用組件的方法。

解決方案:類型庫導入器 (Tlbimp.exe)

  1. 定位 COM 檔:%windir%\system32\WSHom.Ocx (即 WScript.Shell)。
  2. 複製備份,開啟 Visual Studio 2005 命令提示字元。
  3. 執行轉換命令:
Tlbimp.exe WSHom.Ocx /out:WSHomx.dll
  1. 將生成的 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;
}

優勢總結

  • 繞過 ASP.NET 執行身分權限限制,成功調用外部程式修改檔案。
  • 比傳統 ASP 寫法更符合 .NET 開發習慣,強型別、IntelliSense 支援。
  • 無需註冊 COM 元件,部署簡單 (僅放入 bin 目錄)。

此法同樣適用於其他需伺服器端執行外部命令的場景,解決權限困擾。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved