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