[C#]注册表操作
创建/修改
RegistryKey theRegistryKey = Registry.CurrentUser; theRegistryKey.CreateSubKey("MyApp"); theRegistryKey.SetValue("MyValue0", "MyValueData0"); theRegistryKey.SetValue("MyValue1", "MyValueData1"); RegistryKey theRegistrySubKey = Registry.CurrentUser.CreateSubKey("MyApp\\DEMO"); theRegistrySubKey.SetValue("MyValue2", "MyValueData2"); theRegistrySubKey.SetValue("MyValue3", "MyValueData3");
theRegistryKey.Close();
theRegistrySubKey.Close();
打开/读取
RegistryKey theRegistryKey = Registry.CurrentUser; //RegistryKey theRegistrySubKey = Registry.CurrentUser.CreateSubKey("MyApp\\DEMO"); RegistryKey theRegistrySubKey = Registry.CurrentUser.OpenSubKey("MyApp\\DEMO"); Console.WriteLine(theRegistryKey.GetValue("MyValue0")); Console.WriteLine(theRegistryKey.GetValue("MyValue1")); Console.WriteLine(theRegistrySubKey.GetValue("MyValue2")); Console.WriteLine(theRegistrySubKey.GetValue("MyValue3")); theRegistryKey.Close(); theRegistrySubKey.Close();
删除
RegistryKey theRegistryKey = Registry.CurrentUser; RegistryKey theRegistrySubKey = Registry.CurrentUser.OpenSubKey("MyApp",true); theRegistryKey.DeleteValue("MyValue0"); theRegistrySubKey.DeleteSubKeyTree("DEMO"); theRegistryKey.DeleteSubKey("MyApp"); theRegistryKey.Close(); theRegistrySubKey.Close();
判断项是否存在
private bool RegExist() { string[] strSubNames; RegistryKey theRegistryKey = Registry.CurrentUser; RegistryKey theRegistrySubKey = theRegistryKey.OpenSubKey("MyApp\\DEMO"); strSubNames = theRegistrySubKey.GetSubKeyNames(); foreach (string strSubName in strSubNames) { if (strSubName == "MyValue0") { theRegistryKey.Close(); theRegistrySubKey.Close(); return true; } } theRegistryKey.Close(); theRegistrySubKey.Close(); return false; }
判断值是否存在
private bool RegKeyExist() { string[] strKeyNames; RegistryKey theRegistryKey = Registry.CurrentUser; RegistryKey theRegistrySubKey = theRegistryKey.OpenSubKey("MyApp\\DEMO"); strKeyNames = theRegistrySubKey.GetValueNames(); foreach (string strKeyName in strKeyNames) { if (strKeyName == "MyValue2") { theRegistryKey.Close(); theRegistrySubKey.Close(); return true; } } theRegistryKey.Close(); theRegistrySubKey.Close(); return false; }