有時會遇到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; }