true); RegistryKey OpenPath = test.OpenSubKey("OpenLog"

时间:2021-09-29 07:37:38

一、引入定名空间:

using Microsoft.Win32;

二、创建注册表项:CreateSubKey(name)要领

添加SubKey时候首先要打开一个表项,并设置参数为true,才华告成创建子项

//给要创建的注册表设置一个变量,使用更便利
private string RegistFileName = "test";

/// <summary> /// 创建一个test注册表项,下面包罗OpenLog,和SaveLog两个子项 /// </summary> private void CreateRegistFile() {
  //SOFTWARE在LocalMachine分支下
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE",true); RegistryKey software = key.CreateSubKey(RegistFileName); RegistryKey test = key.OpenSubKey(RegistFileName,true); RegistryKey Savekey = test.CreateSubKey("SaveLog"); }

三、删除注册表项:DeleteSubKey(name,true)要领

RegistryKey key = Registry.LocalMachine; RegistryKey software = key.OpenSubKey("SOFTWARE", true); RegistryKey test = software.OpenSubKey(RegistFileName, true); test.DeleteSubKey("SaveLog",true);

四、添加键值:SetValue(name,value)要领

/// <summary> /// 将path写入OPenLog子项 /// </summary> private void writeToRegistFile(string path) {
  RegistryKey key = Registry.LocalMachine;
  RegistryKey software = key.OpenSubKey("SOFTWARE", true);
  RegistryKey test = software.OpenSubKey(RegistFileName, true);
  RegistryKey OpenPath = test.OpenSubKey("OpenLog",true);
  //"name"是该键值的name,,相当于一个别号,可自行设置
  OpenPath.SetValue("name", path); }

五、删除键值:DeleteValue(name)要领

RegistryKey key = Registry.LocalMachine; RegistryKey software = key.OpenSubKey("SOFTWARE", true); RegistryKey test = software.OpenSubKey(RegistFileName, true);
RegistryKey OpenPath = test.OpenSubKey("SaveLog",true);
//删除SaveLog子项下的名为SaveLog的子键
OpenPath.DeleteValue("name");

六、判断注册表项是否存在:

/// <summary> /// 判断注册表项是否存在 /// </summary> /// <returns>bool</returns> private bool IsRegeditItemExist() {   string[] subkeyNames;   RegistryKey key = Registry.LocalMachine;   RegistryKey software = key.OpenSubKey("SOFTWARE");   subkeyNames = software.GetSubKeyNames();   //在这里我是判断test表项是否存在   foreach (string keyName in subkeyNames)   {     if (keyName == RegistFileName)     {       key.Close();       return true;     }   }   key.Close();   return false; }

七、判断键值是否存在:

/// <summary> /// 判断该路径是否已经存在 /// </summary> /// <param>路径</param> /// <returns></returns> private bool IsRegeditKeyExit(string name) {string[] saveSubkeyNames; RegistryKey key = Registry.LocalMachine; RegistryKey software = key.OpenSubKey("SOFTWARE", true); RegistryKey test = software.OpenSubKey(RegistFileName, true); RegistryKey Savekey = test.OpenSubKey("SaveLog", true);
  //获取该子项下的所有键值的名称saveSubkeyNames saveSubkeyNames = Savekey.GetSubKeyNames(); foreach(string keyName in openSubkeyNames) { if(keyName == name) { key.Close(); return false; } } key.Close(); return true; }

注:如果没有该注册表项或键值,则返回的值为空值,若不经措置惩罚惩罚运行措施会抛出异常。