在C#的项目中,有的时候为了安全性和易管理型考虑,往往把项目敏感的配置信息写入注册表中。了解如何读取是关键,其次还包括创建子键,以及设置键值等操作,代码如下。
附上一个管理注册表的示例。
1. 主程序。

Main
1
static void Main(string[] args)
2

{
3
Program p = new Program();
4
p.getRegistry(RegistryHive.LocalMachine, @"SOFTWARE\Test");//读取注册表子键,带有类型判断
5
6
Console.WriteLine(p.getRegistry(RegistryHive.LocalMachine, @"SOFTWARE\Test", "Str"));//读取具体的键值
7
Console.WriteLine(p.getRegistry(RegistryHive.CurrentUser, @"Console", "FaceName"));
8
9
RegSecurity();//带安全验证的注册表操作
10
11
Console.ReadLine();
12
13
}
2. 权限操作和创建注册表。

RegSecurity
1
private static void RegSecurity()
2

{
3
const string TestKey = "TestKey3927";
4
RegistryKey cu = Registry.CurrentUser;
5
6
string user = Environment.UserDomainName + "\\" + Environment.UserName;
7
8
System.Security.AccessControl.RegistrySecurity mSec = new System.Security.AccessControl.RegistrySecurity();
9
System.Security.AccessControl.RegistryAccessRule rule = new System.Security.AccessControl.RegistryAccessRule(user, System.Security.AccessControl.RegistryRights.ReadKey | System.Security.AccessControl.RegistryRights.WriteKey | System.Security.AccessControl.RegistryRights.Delete, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow);
10
mSec.AddAccessRule(rule);
11
12
rule = new System.Security.AccessControl.RegistryAccessRule(user, System.Security.AccessControl.RegistryRights.ChangePermissions, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.InheritOnly | System.Security.AccessControl.PropagationFlags.NoPropagateInherit, System.Security.AccessControl.AccessControlType.Allow);
13
mSec.AddAccessRule(rule);
14
15
ShowSecurity(mSec);
16
17
RegistryKey rk = cu.CreateSubKey(TestKey, RegistryKeyPermissionCheck.ReadWriteSubTree, mSec);
18
RegistryKey rkChild = rk.CreateSubKey("ChildKey", RegistryKeyPermissionCheck.ReadWriteSubTree);
19
RegistryKey rkGrandChild = rkChild.CreateSubKey("GrandChildKey", RegistryKeyPermissionCheck.ReadWriteSubTree);
20
rkGrandChild.SetValue("ValueIs", "This is the value!", RegistryValueKind.String);
21
22
Show(rk);
23
Show(rkChild);
24
Show(rkGrandChild);
25
26
rkGrandChild.Close();
27
rkChild.Close();
28
rk.Close();
29
cu.DeleteSubKeyTree(TestKey);
30
}
3. 显示注册表键值

Show
1
private static void Show(RegistryKey rk)
2

{
3
Console.WriteLine(rk.Name);
4
ShowSecurity(rk.GetAccessControl());
5
}
4. 显示安全信息

ShowSecurity
1
private static void ShowSecurity(System.Security.AccessControl.RegistrySecurity security)
2

{
3
Console.WriteLine("\r\nCurrent access rules:\r\n");
4
foreach (System.Security.AccessControl.RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
5
{
6
Console.WriteLine("User:{0}", ar.IdentityReference);
7
Console.WriteLine("Type:{0}", ar.AccessControlType);
8
Console.WriteLine("Rights:{0}", ar.RegistryRights);
9
Console.WriteLine("Inheritance:{0}", ar.InheritanceFlags);
10
Console.WriteLine("Propagation:{0}", ar.PropagationFlags);
11
Console.WriteLine("Inherited?{0}", ar.IsInherited);
12
Console.WriteLine();
13
}
14
}
5. 读取注册表

getRegistry
1
private string getRegistry(RegistryHive hive, string subKey, string value)
2

{
3
RegistryKey regKey = null;
4
switch (hive)
5
{
6
case RegistryHive.LocalMachine:
7
regKey = Registry.LocalMachine;
8
break;
9
case RegistryHive.CurrentUser:
10
regKey = Registry.CurrentUser;
11
break;
12
default:
13
regKey = null;
14
break;
15
}
16
17
RegistryKey key = regKey.OpenSubKey(subKey);
18
19
string str = Registry.GetValue(key.ToString(), value, "Get the value from the registry failed!").ToString();
20
21
return str;
22
}
6. 带类型判断的读取注册表。

Code
1
2
private void getRegistry(RegistryHive hive,string subKey)
3

{
4
RegistryKey regKey = null;
5
switch (hive)
6
{
7
case RegistryHive.LocalMachine:
8
regKey = Registry.LocalMachine;
9
break;
10
case RegistryHive.CurrentUser:
11
regKey = Registry.CurrentUser;
12
break;
13
default:
14
regKey = null;
15
break;
16
}
17
18
RegistryKey key = regKey.OpenSubKey(subKey);
19
20
string[] strr = key.GetValueNames();
21
foreach (string s in strr)
22
{
23
RegistryValueKind rvk = key.GetValueKind(s);
24
switch (rvk)
25
{
26
case RegistryValueKind.String:
27
string values = (string)key.GetValue(s);
28
Console.Write("\r\n {0} ({1}) = \"
{2}\"", s, rvk, values);
29
//for (int i = 1; i < values.Length; i++)
30
//{
31
// Console.Write(", \"{0}\"", values[i]);
32
//}
33
Console.WriteLine();
34
break;
35
case RegistryValueKind.Binary:
36
byte bytes = (byte)key.GetValue(s);
37
Console.Write("\r\n {0} ({1}) = {2:X2}", s, rvk, bytes);
38
//for (int i = 1; i < bytes.Length; i++)
39
//{
40
// // Display each byte as two hexadecimal digits.
41
// Console.Write(" {0:X2}", bytes[i]);
42
//}
43
Console.WriteLine();
44
break;
45
default:
46
break;
47
}
48
}
49
}
操作注册表代码下载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述