亲宝软件园·资讯

展开

C#操作注册表 使用C#在注册表中保存信息的例子

人气:0
想了解使用C#在注册表中保存信息的例子的相关内容吗,在本文为您仔细讲解C#操作注册表的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,操作注册表,下面大家一起来学习吧。

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

复制代码 代码如下:

using System;

namespace Backend
{
    public class RegistryStorage
    {
        public static PageVisibility OpenAfterStart()
        {
            Microsoft.Win32.RegistryKey registryKey;
            PageVisibility visibility = PageVisibility.Visible;

            // HKCU\Software\RegeditStorage
            registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\RegistryStorage");
            if (registryKey != null)
            {
                visibility = (string)registryKey.GetValue("PageVisibility") == PageVisibility.Hide.ToString() ?
                    PageVisibility.Hide : PageVisibility.Visible;
                registryKey.Close();
            }

            return visibility;
        }

        public static void SaveBeforeExit(PageVisibility visibility)
        {
            Microsoft.Win32.RegistryKey registryKey;

            // HKCU\Software\RegeditStorage
            registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\RegistryStorage");
            registryKey.SetValue("PageVisibility", visibility.ToString());
            registryKey.Close();
        }
    }

    public enum PageVisibility
    {
        Visible,
        Hide
    }
}

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

复制代码 代码如下:

using System;
using System.Diagnostics;

namespace Backend.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // 存值
            RegistryStorage.SaveBeforeExit(PageVisibility.Hide);
            // 取值
            PageVisibility visibility = RegistryStorage.OpenAfterStart();
            // 验证
            Debug.Assert(visibility == PageVisibility.Hide);

  
            // 存值
            RegistryStorage.SaveBeforeExit(PageVisibility.Visible);
            // 取值
            visibility = RegistryStorage.OpenAfterStart();
            // 验证
            Debug.Assert(visibility == PageVisibility.Visible);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

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

加载全部内容

相关教程
猜你喜欢
用户评论