讓進程調用許可權問題見鬼去吧

來源:互聯網
上載者:User

最近需要用到在伺服器端調用一個C++組件,因為涉及到組件會去修改某個目標檔案,所以在.NET裡面使用Process對象死活報出唯讀錯誤.

到處找資料查詢,大部分人都說涉及到調用組件修改檔案的問題,.NET是不允許這樣做的.我差點沒昏掉.但是記得以前寫ASP的時候使用WScript.Shell對象好像是可以做到的.於是開始使用ASP進行實驗,居然沒有報任何錯誤,一陣狂喜.

然後又給我找到一條有用的資訊,可以將WScript.Shell轉換成DLL,使用.net直接調用方法.方法如下:

·將COM組件轉化為.NET組件

微軟給我們提供了類型庫匯入器(Type Library Importer),經過它的轉換,我們就可以使用COM組件了。轉換之後,會有一個dll檔案,需要放到Web目錄的bin目錄下組件才可以被使用。

雖然這樣多了一個dll,但是這個dll不需要註冊就可直接使用,非常方便,這也是ASP.NET與ASP的區別之一。哈哈,有的BT管理員沒事要刪除“有害”的組件,現在他也沒辦法了吧^_^

WScript.Shell對象是%windir%\system32\WSHom.Ocx,我們把它copy出來拿,開啟Visual Studio 2005 命令提示,使用類型庫匯入器轉換:Tlbimp.exe WSHom.Ocx /out: WSHomx.dll

然後把WSHomx.dll放到WEB目錄的bin下面。接著寫代碼咯,與前面的代碼有少許不同。

於是問題終於順利解決,而且發現比使用ASP的寫法更方便.

全部代碼如下:

程式碼

public void Receive()
     {
       string request = RequestHelper.RequestGetValue("fileName");
       WshShell Cmd = new WshShell();
       string result = Cmd.Exec(VoiceTestPath + " " + VoiceOutputPath + request + ".wav 2").StdOut.ReadAll();
       HttpHelper.ResponseWrite(result);
       //調用進程的方法無效
       //if (!string.IsNullOrEmpty(request))
       //{
       //  HttpHelper.ResponseWrite(ExecuteByProcess(VoiceTestPath, VoiceOutputPath + request + ".wav 2"));
       //}
     }
     /// <summary>
     /// 調用一個進程執行轉換
     /// </summary>
     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; //重新導向輸出,而不是默認的顯示在dos控制臺
       p.StartInfo.FileName = CommandPath; //轉換器路徑
       p.StartInfo.Arguments = Arguments;
       return StartProcess(p, 500);
     }
     /// <summary>
     /// 啟動進程
     /// </summary>
     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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.