某次需要使用C#對注冊表進行操作,不過卻發現沒有權限,研究了以下發現是當前系統用戶的問題。除非當前系統用戶是Administrator,否則就會給你拋出一個異常。后來在網上發現了一個方法,原來C#也可以獲取用戶的系統管理員權限的,雖然需要用戶進行確認。
這里我對Oracle軟件的一個鍵進行了操作,想要將值改為一個指定的字符。在進入注冊表后,進行提升權限操作,獲取權限后執行bat文件和reg文件。當然,如果不想用bat和reg文件也可以,不過那就需要在操作注冊表之前進行提升權限操作了。
try { //操作注冊表進入指定鍵值對 Microsoft.Win32.RegistryKey RegistryRoot = Microsoft.Win32.Registry.LocalMachine; string[] path = new string[] { "SOFTWARE", "ORACLE", "KEY_OraDb10g_home1" }; foreach (string p in path) { if (RegistryRoot != null) RegistryRoot = RegistryRoot.OpenSubKey(p); } //判斷鍵值對是否為空 if (RegistryRoot != null) { object value = RegistryRoot.GetValue("NLS_LANG"); //如果鍵值不符合標准,則修改注冊表鍵值對 if (value == null || !value.ToString().ToUpper().Contains("ZHS16GBK")) { System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判斷當前登錄用戶是否為管理員 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { //如果是管理員,則直接運行 System.Diagnostics.Process.Start("regedit.exe", "/s oracle_char.reg"); } else { //創建啟動對象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; //startInfo.FileName = Application.ExecutablePath; startInfo.FileName = string.Format("{0}oracle_char.bat", AppDomain.CurrentDomain.BaseDirectory); //設置啟動動作,確保以管理員身份運行 startInfo.Verb = "runas"; System.Diagnostics.Process.Start(startInfo); } } } } catch { }
bat文件:
@echo off %1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit cd /d "%~dp0" @FOR %%A IN (oracle_char.reg) DO (REGEDIT /S %%A)
reg文件:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_OraDb10g_home1]
"NLS_LANG"="SIMPLIFIED CHINESE_CHINA.ZHS16GBK"
在運行提升權限操作時,程序會彈出一個窗口,要求用戶提升權限。Adminsitrator用戶有密碼的話輸入密碼,沒有密碼點擊一下確認按鈕就可以了。
不過這個時候可能會出現一個問題,就是在彈出要求用戶提升系統權限的時候,主進程的代碼會繼續向下執行,這個時候,就需要調用下面的一個方法。
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
process.WaitForExit();
方法WaitForExit是表示等待相關聯進程的。如果不加入參數,則會表示軟件主進程會無限期等待關聯進程,也就是要求用戶提升系統權限的彈出框。只有用戶進行操作之后才會繼續向下執行。
不過值得注意的是,如果這個時候用戶點擊按鈕“否”的話,會拋出一個異常,叫做“用戶取消操作”。