本文實例講述了C#操作注冊表的方法。分享給大家供大家參考,具體如下:
下面我們就來用.NET下托管語言C#注冊表操作,主要內容包括:注冊表項的創建,打開與刪除、鍵值的創建(設置值、修改),讀取和刪除、判斷注冊表項是否存在、判斷鍵值是否存在。
準備工作:
1. 要操作注冊表,我們必須要引入必要的命名空間:
2. 命名空間里面提供了一個類:RegistryKey 利用它我們可以定位到注冊表最開頭的分支:
ClassesRoot,CurrentUser,Users,LocalMachine,CurrentConfig
如:
3. 在操作的過程中涉及到子分支,要用//進行深入,單個/會報錯!
4. 最后要調用RegistryKey對象的Close()關閉對注冊表的修改~~~
5. 以下我們的例子都是在LocalMachine分支下,請注意。
一、C#注冊表項的創建,打開與刪除
1. 創建
創建注冊表項主要用到RegistryKey 的CreateSubKey()方法。如:
RegistryKey key = Registry.LocalMachine;RegistryKey software = key.CreateSubKey("software//test");//在HKEY_LOCAL_MACHINE/SOFTWARE下新建名為test的注冊表項。如果已經存在則不影響!
2. 打開
打開注冊表項主要用到RegistryKey 的OpenSubKey()方法。如:
注意,如果該注冊表項不存在,這調用這個方法會拋出異常
RegistryKey key = Registry.LocalMachine;RegistryKey software = key.OpenSubKey("software//test",true);//注意該方法后面還可以有一個布爾型的參數,true表示可以寫入。
3. 刪除
刪除注冊表項主要用到RegistryKey 的DeleteSubKey()方法。如:
RegistryKey key = Registry.LocalMachine;key.DeleteSubKey("software//test",true); //該方法無返回值,直接調用即可key.Close();
注意,如果該注冊表項不存在,這調用這個方法會拋出異常
二、鍵值的創建(設置值、修改),讀取和刪除
1. 創建(設置值、修改)
對鍵值的創建修改等操作主要用到RegistryKey 的SetValue()方法
RegistryKey key = Registry.LocalMachine;RegistryKey software = key.OpenSubKey("software//test",true); //該項必須已存在software.SetValue("test", "武林網");//在HKEY_LOCAL_MACHINE/SOFTWARE/test下創建一個名為“test”,值為“武林網”的鍵值。如果該鍵值原本已經存在,則會修改替換原來的鍵值,如果不存在則是創建該鍵值。// 注意:SetValue()還有第三個參數,主要是用于設置鍵值的類型,如:字符串,二進制,Dword等等~~默認是字符串。如:// software.SetValue("test", "0", RegistryValueKind.DWord); //二進制信息Key.Close();
2. 讀取
string info = "";RegistryKey Key;Key = Registry.LocalMachine;myreg = Key.OpenSubKey("software//test");// myreg = Key.OpenSubKey("software//test",true);info = myreg.GetValue("test").ToString();myreg.Close();
info結果為:武林網
3:刪除
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software//test", true);delKey.DeleteValue("test");delKey.Close();
細心的讀者可能發現了第二個例子中OpenSubKey()方法參數與其他例子的不同。
如果你要修改鍵值,包括創建、設置、刪除鍵值等都要在方法后面加個布爾參數,設置為true,表示可寫可改;如果僅僅只是讀取鍵值可以不加,此時可寫關閉,你不能再往里寫值(當然,你要加也可以true)!
還有讀者提到讀寫默認鍵值的問題,主要在設置、讀取的方法中將鍵名置空則就是對默認鍵值的操作。
如:
三、判斷注冊表項是否存在
private bool IsRegeditItemExist() { string [] subkeyNames; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey("SOFTWARE"); //RegistryKey software = hkml.OpenSubKey("SOFTWARE", true); subkeyNames = software.GetSubKeyNames(); //取得該項下所有子項的名稱的序列,并傳遞給預定的數組中 foreach (string keyName in subkeyNames) //遍歷整個數組 { if (keyName == "test") //判斷子項的名稱 { hkml.Close(); return true ; } } hkml.Close(); return false; }
四、判斷鍵值是否存在
private bool IsRegeditKeyExit(){ string[] subkeyNames; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey("SOFTWARE//test"); //RegistryKey software = hkml.OpenSubKey("SOFTWARE//test", true); subkeyNames = software.GetValueNames(); //取得該項下所有鍵值的名稱的序列,并傳遞給預定的數組中 foreach (string keyName in subkeyNames) { if (keyName == "test") //判斷鍵值的名稱 { hkml.Close(); return true; } } hkml.Close(); return false;}
補充:x32軟件在x64系統下操作注冊表,會自動轉向到Wow6432Node,為了控制不轉向,使用以下代碼:
/// <summary>/// 獲得根節點的句柄,常數是固定的/// </summary>/// <param name="hive"></param>/// <returns></returns>public static IntPtr GetHiveHandle(RegistryHive hive){ IntPtr preexistingHandle = IntPtr.Zero; IntPtr HKEY_CLASSES_ROOT = new IntPtr(-2147483648); IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647); IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646); IntPtr HKEY_USERS = new IntPtr(-2147483645); IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(-2147483644); IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643); IntPtr HKEY_DYN_DATA = new IntPtr(-2147483642); switch (hive) { case RegistryHive.ClassesRoot: preexistingHandle = HKEY_CLASSES_ROOT; break; case RegistryHive.CurrentUser: preexistingHandle = HKEY_CURRENT_USER; break; case RegistryHive.LocalMachine: preexistingHandle = HKEY_LOCAL_MACHINE; break; case RegistryHive.Users: preexistingHandle = HKEY_USERS; break; case RegistryHive.PerformanceData: preexistingHandle = HKEY_PERFORMANCE_DATA; break; case RegistryHive.CurrentConfig: preexistingHandle = HKEY_CURRENT_CONFIG; break; case RegistryHive.DynData: preexistingHandle = HKEY_DYN_DATA; break; } return preexistingHandle;}
使用:
/// <summary>/// 操作注冊表/// </summary>/// <param name="hive">根級別的名稱</param>/// <param name="path">不包括根級別的名稱</param>/// <param name="parameters">項/(值/值類型) 參數</param>/// <param name="view">注冊表視圖</param>[RegistryPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]public static void OperateReg(RegistryHive hive, string path, Dictionary<string, string[]> parameters, RegistryView view){ SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true); RegistryKey r = RegistryKey.FromHandle(handle, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);//一般情況是使用如下代碼://RegistryKey rk = Registry.LocalMachine.CreateSubKey(path); if (parameters == null && parameters.Count <= 0) return; List<string> keys = parameters.Keys.ToList(); for (int i = 0; i < parameters.Count; i++) { //string to RegistryValueKind RegistryValueKind rv = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), parameters[keys[i]][1].ToString(), true); r.SetValue(keys[i], parameters[keys[i]][0], rv); }}
例子:
public static void RegisterScreenCapture(string targetDir, string guid, bool is64BitLync){ if (string.IsNullOrEmpty(guid)) guid = "{541a4dc3-50dc-4b4f-a38d-0ed1d360ca6b}"; Dictionary<string, string[]> paraCapture = new Dictionary<string, string[]>(); paraCapture["Name"] = new string[] { "ScreenCapture", RegistryValueKind.String.ToString() }; paraCapture["Path"] = new string[] { string.Format("{0}IcoLync.ScreenCapture.exe", targetDir), RegistryValueKind.String.ToString() }; paraCapture["Extensiblemenu"] = new string[] { "ConversationWindowActions", RegistryValueKind.String.ToString() }; paraCapture["SessionType"] = new string[] { "0", RegistryValueKind.DWord.ToString() }; RegistryView rv; if (is64BitLync) rv = RegistryView.Registry64; else rv = RegistryView.Default; OperateReg(RegistryHive.LocalMachine, string.Format(@"SOFTWARE/Microsoft/Office/15.0/Lync/SessionManager/Apps/{0}", guid), paraCapture, rv);}
剛才經過測試,不需要GetHiveHandl()也行(我也不知道什么需要);
OperateReg()方法中一二行代碼改為
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答