随笔 - 46  文章 - 0  评论 - 136  阅读 - 11万

C#实现在注册表中保存信息

最近做的项目需要在注册表中记录一些用户设置,方便在程序下次启动时读取设置,应用上次用户保存的设置,挺简单的。

写出来,方便记忆,以后要用,可以直接改改就能用。

复制代码
 1 using System;
 2 
 3 namespace Backend
 4 {
 5     public class RegistryStorage
 6     {
 7         public static PageVisibility OpenAfterStart()
 8         {
 9             Microsoft.Win32.RegistryKey registryKey;
10             PageVisibility visibility = PageVisibility.Visible;
11 
12             // HKCU\Software\RegeditStorage
13             registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\RegistryStorage");
14             if (registryKey != null)
15             {
16                 visibility = (string)registryKey.GetValue("PageVisibility") == PageVisibility.Hide.ToString() ?
17                     PageVisibility.Hide : PageVisibility.Visible;
18                 registryKey.Close();
19             }
20 
21             return visibility;
22         }
23 
24         public static void SaveBeforeExit(PageVisibility visibility)
25         {
26             Microsoft.Win32.RegistryKey registryKey;
27 
28             // HKCU\Software\RegeditStorage
29             registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\RegistryStorage");
30             registryKey.SetValue("PageVisibility", visibility.ToString());
31             registryKey.Close();
32         }
33     }
34 
35     public enum PageVisibility
36     { 
37         Visible,
38         Hide
39     }
40 }
复制代码

代码很容易理解,下面添加一点代码来测试一下。

复制代码
 1 using System;
 2 using System.Diagnostics;
 3 
 4 namespace Backend.Test
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             // 存值 
11             RegistryStorage.SaveBeforeExit(PageVisibility.Hide);
12             // 取值
13             PageVisibility visibility = RegistryStorage.OpenAfterStart();
14             // 验证
15             Debug.Assert(visibility == PageVisibility.Hide);
16 
17 
18             // 存值
19             RegistryStorage.SaveBeforeExit(PageVisibility.Visible);
20             // 取值
21             visibility = RegistryStorage.OpenAfterStart();
22             // 验证
23             Debug.Assert(visibility == PageVisibility.Visible);
24 
25             Console.WriteLine("Press any key to exit.");
26             Console.ReadKey();
27         }
28     }
29 }
复制代码

最后,上一张修改后的注册表截图:

 

posted on   ProJKY  阅读(4565)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示