注册表操作需要获取管理员权限,可以将exe设置为管理员启动。具体操作代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| /// <summary> /// 注册表 HKEY_LOCAL_MACHINE/SOFTWARE 节点下 /// </summary> public static class RegistryHelper { private const string Node = "SOFTWARE";
public static string GetRegistryData(string node, string key) { string registData; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey(Node, true); RegistryKey dir = software.OpenSubKey(node, true); registData = dir.GetValue(key)?.ToString(); return registData; }
/// <summary> /// 写入注册表 /// </summary> /// <param name="node">节点</param> /// <param name="name">注册项名称</param> /// <param name="value">注册项值</param> public static void WriteRegistry(string node, string name, string value) { RegistryKey hklm = Registry.LocalMachine; RegistryKey software = hklm.OpenSubKey(Node, true); RegistryKey dir = software.CreateSubKey(node); if (dir != null) dir.SetValue(name, value); }
/// <summary> /// 删除注册表 /// </summary> /// <param name="node"></param> /// <param name="name"></param> public static void DeleteRegistry(string node, string name) { string[] aimnames; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey(Node, true); RegistryKey dir = software.OpenSubKey(node, true); aimnames = dir.GetSubKeyNames(); foreach (string aimKey in aimnames) { if (aimKey == name) dir.DeleteSubKeyTree(name); } }
/// <summary> /// 查询节点是否存在 /// </summary> /// <param name="node"></param> /// <param name="name"></param> /// <returns></returns> public static bool IsRegeditExit(string node, string name) { bool _exit = false; string[] subkeyNames; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey(Node, true); RegistryKey dir = software.OpenSubKey(node, true); subkeyNames = dir.GetSubKeyNames(); foreach (string keyName in subkeyNames) { if (keyName == name) { _exit = true; return _exit; } } return _exit; } }
|