C#操作注冊(cè)表的方法詳解
本文實(shí)例講述了C#操作注冊(cè)表的方法。分享給大家供大家參考,具體如下:
下面我們就來(lái)用.NET下托管語(yǔ)言C#注冊(cè)表操作,主要內(nèi)容包括:注冊(cè)表項(xiàng)的創(chuàng)建,打開(kāi)與刪除、鍵值的創(chuàng)建(設(shè)置值、修改),讀取和刪除、判斷注冊(cè)表項(xiàng)是否存在、判斷鍵值是否存在。
準(zhǔn)備工作:
1. 要操作注冊(cè)表,我們必須要引入必要的命名空間:
在這個(gè)命名空間里面包含了許多注冊(cè)表相關(guān)的類(lèi),足夠我們使用了~~
2. 命名空間里面提供了一個(gè)類(lèi):RegistryKey 利用它我們可以定位到注冊(cè)表最開(kāi)頭的分支:
ClassesRoot,CurrentUser,Users,LocalMachine,CurrentConfig
如:
3. 在操作的過(guò)程中涉及到子分支,要用\\進(jìn)行深入,單個(gè)\會(huì)報(bào)錯(cuò)!
4. 最后要調(diào)用RegistryKey對(duì)象的Close()關(guān)閉對(duì)注冊(cè)表的修改~~~
5. 以下我們的例子都是在LocalMachine分支下,請(qǐng)注意。
一、C#注冊(cè)表項(xiàng)的創(chuàng)建,打開(kāi)與刪除
1. 創(chuàng)建
創(chuàng)建注冊(cè)表項(xiàng)主要用到RegistryKey 的CreateSubKey()方法。如:
RegistryKey key = Registry.LocalMachine; RegistryKey software = key.CreateSubKey("software\\test"); //在HKEY_LOCAL_MACHINE\SOFTWARE下新建名為test的注冊(cè)表項(xiàng)。如果已經(jīng)存在則不影響!
2. 打開(kāi)
打開(kāi)注冊(cè)表項(xiàng)主要用到RegistryKey 的OpenSubKey()方法。如:
注意,如果該注冊(cè)表項(xiàng)不存在,這調(diào)用這個(gè)方法會(huì)拋出異常
RegistryKey key = Registry.LocalMachine; RegistryKey software = key.OpenSubKey("software\\test",true); //注意該方法后面還可以有一個(gè)布爾型的參數(shù),true表示可以寫(xiě)入。
3. 刪除
刪除注冊(cè)表項(xiàng)主要用到RegistryKey 的DeleteSubKey()方法。如:
RegistryKey key = Registry.LocalMachine; key.DeleteSubKey("software\\test",true); //該方法無(wú)返回值,直接調(diào)用即可 key.Close();
注意,如果該注冊(cè)表項(xiàng)不存在,這調(diào)用這個(gè)方法會(huì)拋出異常
二、鍵值的創(chuàng)建(設(shè)置值、修改),讀取和刪除
1. 創(chuàng)建(設(shè)置值、修改)
對(duì)鍵值的創(chuàng)建修改等操作主要用到RegistryKey 的SetValue()方法
RegistryKey key = Registry.LocalMachine; RegistryKey software = key.OpenSubKey("software\\test",true); //該項(xiàng)必須已存在 software.SetValue("test", "腳本之家"); //在HKEY_LOCAL_MACHINE\SOFTWARE\test下創(chuàng)建一個(gè)名為“test”,值為“腳本之家”的鍵值。如果該鍵值原本已經(jīng)存在,則會(huì)修改替換原來(lái)的鍵值,如果不存在則是創(chuàng)建該鍵值。 // 注意:SetValue()還有第三個(gè)參數(shù),主要是用于設(shè)置鍵值的類(lèi)型,如:字符串,二進(jìn)制,Dword等等~~默認(rèn)是字符串。如: // software.SetValue("test", "0", RegistryValueKind.DWord); //二進(jìn)制信息 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結(jié)果為:腳本之家
3:刪除
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software\\test", true); delKey.DeleteValue("test"); delKey.Close();
細(xì)心的讀者可能發(fā)現(xiàn)了第二個(gè)例子中OpenSubKey()方法參數(shù)與其他例子的不同。
如果你要修改鍵值,包括創(chuàng)建、設(shè)置、刪除鍵值等都要在方法后面加個(gè)布爾參數(shù),設(shè)置為true,表示可寫(xiě)可改;如果僅僅只是讀取鍵值可以不加,此時(shí)可寫(xiě)關(guān)閉,你不能再往里寫(xiě)值(當(dāng)然,你要加也可以true)!
還有讀者提到讀寫(xiě)默認(rèn)鍵值的問(wèn)題,主要在設(shè)置、讀取的方法中將鍵名置空則就是對(duì)默認(rèn)鍵值的操作。
如:
另外,默認(rèn)的鍵值是不能刪除的,所以不要用DeleteValue()方法去刪除,會(huì)拋出異常的!
三、判斷注冊(cè)表項(xiàng)是否存在
private bool IsRegeditItemExist() { string [] subkeyNames; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey("SOFTWARE"); //RegistryKey software = hkml.OpenSubKey("SOFTWARE", true); subkeyNames = software.GetSubKeyNames(); //取得該項(xiàng)下所有子項(xiàng)的名稱(chēng)的序列,并傳遞給預(yù)定的數(shù)組中 foreach (string keyName in subkeyNames) //遍歷整個(gè)數(shù)組 { if (keyName == "test") //判斷子項(xiàng)的名稱(chēng) { 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(); //取得該項(xiàng)下所有鍵值的名稱(chēng)的序列,并傳遞給預(yù)定的數(shù)組中 foreach (string keyName in subkeyNames) { if (keyName == "test") //判斷鍵值的名稱(chēng) { hkml.Close(); return true; } } hkml.Close(); return false; }
補(bǔ)充:x32軟件在x64系統(tǒng)下操作注冊(cè)表,會(huì)自動(dòng)轉(zhuǎn)向到Wow6432Node,為了控制不轉(zhuǎn)向,使用以下代碼:
/// <summary> /// 獲得根節(jié)點(diǎn)的句柄,常數(shù)是固定的 /// </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> /// 操作注冊(cè)表 /// </summary> /// <param name="hive">根級(jí)別的名稱(chēng)</param> /// <param name="path">不包括根級(jí)別的名稱(chēng)</param> /// <param name="parameters">項(xiàng)/(值/值類(lèi)型) 參數(shù)</param> /// <param name="view">注冊(cè)表視圖</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); }
剛才經(jīng)過(guò)測(cè)試,不需要GetHiveHandl()也行(我也不知道什么需要);
OperateReg()方法中一二行代碼改為
RegistryKey r = RegistryKey.OpenBaseKey(hive, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C# 使用 Castle 實(shí)現(xiàn) AOP及如何用 Autofac 集成 Castle
這篇文章主要介紹了C# 使用 Castle 實(shí)現(xiàn) AOP及如何用 Autofac 集成 Castle,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02C#實(shí)現(xiàn)實(shí)時(shí)監(jiān)控文件夾變化
在開(kāi)發(fā)各種應(yīng)用程序時(shí),我們經(jīng)常需要對(duì)文件系統(tǒng)中的文件或文件夾進(jìn)行實(shí)時(shí)監(jiān)測(cè),下面就跟隨小編一起來(lái)看看具體如何使用C#實(shí)現(xiàn)這一功能吧2024-03-03C#特性 匿名類(lèi)型與隱式類(lèi)型局部變量使用介紹
這篇文章主要介紹了C#特性-匿名類(lèi)型與隱式類(lèi)型局部變量,需要的朋友可以參考下2014-12-12unity shader實(shí)現(xiàn)較完整光照效果
這篇文章主要為大家詳細(xì)介紹了unity shader實(shí)現(xiàn)較完整光照效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11通過(guò)VS中的數(shù)據(jù)源選擇對(duì)話框簡(jiǎn)單實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接配置[圖]
通過(guò)VS中的數(shù)據(jù)源選擇對(duì)話框簡(jiǎn)單實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接配置[圖]...2007-03-03C# 無(wú)邊框窗體之窗體移動(dòng)實(shí)現(xiàn)代碼
這篇文章介紹了C# 無(wú)邊框窗體之窗體移動(dòng)實(shí)現(xiàn)代碼,有需要的朋友可以參考一下2013-10-10