C# 注冊Dll文件


有時會遇到dll在系統中不存在,需要程序自己去注冊所需的dll文件。

注冊dll 需要用到regsvr32命令,其用法為:
"regsvr32 [/s] [/n] [/u] [/i[:cmdline]] dllname”。其中dllname為dll文件名

參數有如下意義:
/u——反注冊控件
/s——不管注冊成功與否,均不顯示提示框
/c——控制台輸出
/i——跳過控件的選項進行安裝(與注冊不同)
/n——不注冊控件,此選項必須與/i選項一起使用

分享代碼如下:

private bool RegisterDll()
        {
            bool result = true;
            try
            {
                string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XXX.dll");//獲得要注冊的dll的物理路徑
                if (!File.Exists(dllPath))
                {
                    Loger.Write(string.Format("“{0}”目錄下無“XXX.dll”文件!", AppDomain.CurrentDomain.BaseDirectory));
                    return false;
                }
             //拼接命令參數
                string startArgs = string.Format("/s \"{0}\"", dllPath);

                Process p = new Process();//創建一個新進程,以執行注冊動作
                p.StartInfo.FileName = "regsvr32";
                p.StartInfo.Arguments = startArgs;

             //以管理員權限注冊dll文件
                WindowsIdentity winIdentity = WindowsIdentity.GetCurrent(); //引用命名空間 System.Security.Principal
                WindowsPrincipal winPrincipal = new WindowsPrincipal(winIdentity);
                if (!winPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    p.StartInfo.Verb = "runas";//管理員權限運行
                }
                p.Start();
                p.WaitForExit();
                p.Close();
                p.Dispose();
            }
            catch (Exception ex)
            {
                result = false;
         //記錄日志,拋出異常 }
return result; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM