C#中注冊表的操作使用RegistryKey類,創建,讀取和判斷某項是否存在。
1、讀取某一項的值,以判斷.NET Framework 2.0.50727是否安裝為例。
我們知道看.net是否安裝看HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v2.0.50727下的Install的值是否為1。那麼如何讀取呢?下面的代碼可以實現。
RegistryKey machinelocalItem;
RegistryKey softwareItem;
RegistryKey microSoftItem;
RegistryKey docNetItem;
RegistryKey ndpItem;
RegistryKey versionItem;
machinelocalItem = Registry.LocalMachine;
softwareItem = machinelocalItem.OpenSubKey("SOFTWARE");
microSoftItem = softwareItem.OpenSubKey("Microsoft");
docNetItem = microSoftItem.OpenSubKey("NET Framework Setup");
ndpItem = docNetItem.OpenSubKey("NDP");
versionItem = ndpItem.OpenSubKey("v2.0.50727" true);
object installValue = netItem.GetValue("Install");
;
RegistryKey machinelocalItem;
RegistryKey softwareItem;
RegistryKey microSoftItem;
RegistryKey docNetItem;
RegistryKey ndpItem;
RegistryKey versionItem;
machinelocalItem = Registry.LocalMachine;
softwareItem = machinelocalItem.OpenSubKey("SOFTWARE");
microSoftItem = softwareItem.OpenSubKey("Microsoft");
docNetItem = microSoftItem.OpenSubKey("NET Framework Setup");
ndpItem = docNetItem.OpenSubKey("NDP");
versionItem = ndpItem.OpenSubKey("v2.0.50727" true);
object installValue = netItem.GetValue("Install");
完成了讀取。當然這是已知這些項都存在的,如果不確定的項,OpenSubKey時判斷用來讀取的項是否NULL就可以了。
2、創建某項。
還是以上面的為例創建。
RegistryKey machinelocalItem;
RegistryKey softwareItem;
RegistryKey microSoftItem;
RegistryKey docNetItem;
RegistryKey ndpItem;
RegistryKey versionItem;
machinelocalItem = Registry.LocalMachine;
softwareItem = machinelocalItem.CreateSubKey("Software");
microSoftItem = softwareItem.CreateSubKey("Microsoft");
docNetItem = microSoftItem.CreateSubKey("NET Framework Setup");
ndpItem = docNetItem.CreateSubKey("NDP");
versionItem = ndpItem.CreateSubKey("v2.0.50727");
versionItem.SetValue("Install", 1);
RegistryKey machinelocalItem;
RegistryKey softwareItem;
RegistryKey microSoftItem;
RegistryKey docNetItem;
RegistryKey ndpItem;
RegistryKey versionItem;
machinelocalItem = Registry.LocalMachine;
softwareItem = machinelocalItem.CreateSubKey("Software");
microSoftItem = softwareItem.CreateSubKey("Microsoft");
docNetItem = microSoftItem.CreateSubKey("NET Framework Setup");
ndpItem = docNetItem.CreateSubKey("NDP");
versionItem = ndpItem.CreateSubKey("v2.0.50727");
versionItem.SetValue("Install", 1);
完成了創建並賦值。
摘自 白楊樹