弥补学生时代的遗憾~C#注册表情缘

记得当时刚接触C#的时候,喜欢编写各种小软件,而注册表系列和网络系列被当时的我认为大牛的必备技能。直到我研究注册表前一天我都感觉他是那么的高深。

今天正好有空,于是就研究了下注册表系列的操作,也随手封装了一个注册表帮助类。简单记一下,当饭后娱乐

完整Demo研究:https://github.com/dunitian/LoTCodeBase/tree/master/NetCode/0.知识拓展/02.注册表系

这个是一些常用的方法和属性(不全,只是列出了比较常用的一些)【OpenSubKey(string name,bool b)当b为true则表示开了可写权限】

//RegistryKey
//属性:
// ValueCount 检索项中值的计数
// SubKeyCount 获取子项个数

//方法:
// OpenSubKey(string name,bool b) 获取子项 RegistryKey,b为true时代表可写
// GetSubKeyNames() 获取所有子项名称的字符串数组
// GetValueNames() 检索包含与此项关联的所有值名称的字符串数组
// GetValue(string name) 获取指定名称,不存在名称/值对,则返回 null
// CreateSubKey(string subkey) 创建或者打开子项的名称或路径
// SetValue(string name,object value) 创建或者打开子项的名称或路径
// DeleteSubKeyTree(string subkey) 递归删除指定目录,不存在则抛异常
// DeleteSubKey(string subkey,bool b) 删除子项,b为false则当子项不存在时不抛异常
// DeleteValue(string name,bool b) 删除指定的键值,b为false则当子项不存在时不抛异常

先举个简单的案例:

弥补学生时代的遗憾~C#注册表情缘_第1张图片

弥补学生时代的遗憾~C#注册表情缘_第2张图片

代码如下:

//获取一个表示HKLM键的RegistryKey
            RegistryKey rk = Registry.LocalMachine;

            //打开HKLM的子项Software
            RegistryKey subKey = rk.OpenSubKey(@"software");

            //遍历所有子项名称的字符串数组
            foreach (var item in subKey.GetSubKeyNames())
            {
                //以只读方式检索子项
                RegistryKey sonKey = subKey.OpenSubKey(item);

                rtxt.AppendText(string.Format("\n--->{0}<---\nSubKeyCount:{1} ValueCount:{2} FullName:{3}\n==================================\n", item, sonKey.SubKeyCount, sonKey.ValueCount, sonKey.Name));

                //检索包含与此项关联的所有值名称的字符串数组
                foreach (var name in sonKey.GetValueNames())
                {
                    rtxt.AppendText(string.Format("Name:{0} Value:{1} Type:{2}\n", name, sonKey.GetValue(name), sonKey.GetValueKind(name)));
                }
            }

 做个综合的案例:

弥补学生时代的遗憾~C#注册表情缘_第3张图片

代码如下:

public partial class MainForm : Form
    {
        public RegistryKey Reg { get; set; }
        public MainForm()
        {
            InitializeComponent();
            //初始化
            var rootReg = Registry.LocalMachine;
            Reg = rootReg.OpenSubKey("software", true);//开权限
        }

        #region 公用方法
        /// <summary>
        /// 检验是否为空
        /// </summary>
        /// <param name="dntReg"></param>
        private bool KeyIsNull(RegistryKey dntReg)
        {
            if (dntReg == null)
            {
                rtxt.AppendText("注册表中没有dnt注册项\n");
                return true;
            }
            return false;
        }

        /// <summary>
        /// 遍历Key的Value
        /// </summary>
        /// <param name="reg"></param>
        private void ForeachRegKeys(RegistryKey reg)
        {
            rtxt.AppendText(string.Format("\n SubKeyCount:{0} ValueCount:{1} FullName:{2}\n", reg.SubKeyCount, reg.ValueCount, reg.Name));
            foreach (var name in reg.GetValueNames())
            {
                rtxt.AppendText(string.Format("Name:{0} Value:{1} Type:{2}\n", name, reg.GetValue(name), reg.GetValueKind(name)));
            }
        }
        #endregion

        //查
        private void btn1_Click(object sender, EventArgs e)
        {
            var dntReg = Reg.OpenSubKey("dnt");
            if (KeyIsNull(dntReg)) return;
            ForeachRegKeys(dntReg);
            foreach (var item in dntReg.GetSubKeyNames())
            {
                //以只读方式检索子项
                RegistryKey sonKey = dntReg.OpenSubKey(item);
                ForeachRegKeys(sonKey);
            }
        }

        //增
        private void btn2_Click(object sender, EventArgs e)
        {
            var dntReg = Reg.CreateSubKey("dnt");
            dntReg.SetValue("web", "http://www.dkill.net");
            var sonReg = dntReg.CreateSubKey("path");
            sonReg.SetValue("value", "D:\\Program Files\\dnt");
            rtxt.AppendText("添加成功\n");
        }

        //改
        private void btn3_Click(object sender, EventArgs e)
        {
            var dntReg = Reg.OpenSubKey("dnt", true);
            if (KeyIsNull(dntReg)) return;
            dntReg.SetValue("web", "http://dnt.dkill.net");
            rtxt.AppendText("修改成功\n");
        }

        //删
        private void btn4_Click(object sender, EventArgs e)
        {
            try
            {
                #region 删除某个值
                //var dntReg = Reg.OpenSubKey("dnt", true);
                //if (KeyIsNull(dntReg)) return;
                //dntReg.DeleteValue("web", false);
                #endregion
                Reg.DeleteSubKeyTree("dnt", false);
                rtxt.AppendText("删除成功\n");
            }
            catch (ArgumentException ex)
            {
                rtxt.AppendText(ex.ToString());
            }
        }

        private void clearlog_Click(object sender, EventArgs e)
        {
            rtxt.Clear();
        }
    }

Helper类综合实战:(有其他演示,有的电脑会出现权限问题)

 弥补学生时代的遗憾~C#注册表情缘_第4张图片

using Microsoft.Win32;
using System.Collections.Generic;

public static partial class RegistryHelper
{
    #region 节点
    /// <summary>
    /// HKEY_LOCAL_MACHINE 节点
    /// </summary>
    public static RegistryKey RootReg = Registry.LocalMachine;

    /// <summary>
    /// HKEY_LOCAL_MACHINE 下 Software 节点
    /// </summary>
    public static RegistryKey SoftReg = Registry.LocalMachine.OpenSubKey("software", true);

    /// <summary>
    /// 包含有关当前用户首选项的信息。该字段读取 Windows 注册表基项 HKEY_CURRENT_USER
    /// </summary>
    public static RegistryKey CurrentUser = Registry.CurrentUser;

    /// <summary>
    /// HKEY_CURRENT_USER 下 Software 节点
    /// </summary>
    public static RegistryKey UserSoftReg = Registry.CurrentUser.OpenSubKey("software", true);
    #endregion

    #region 查询
    /// <summary>
    /// 根据名称查找Key,有则返回RegistryKey对象,没有则返回null
    /// </summary>
    /// <param name="name">要打开的子项的名称或路径</param>
    /// <param name="b">如果不需要写入权限请选择false</param>
    /// <returns></returns>
    public static RegistryKey FindKey(this RegistryKey reg, string name, bool b = true)
    {
        return reg.OpenSubKey(name, b);
    }

    /// <summary>
    /// 获取(name,value)字典,没有则返回null
    /// </summary>
    /// <param name="reg">当前RegistryKey</param>
    /// <returns></returns>
    public static IDictionary<string, object> GetKeyValueDic(this RegistryKey reg)
    {
        var dic = new Dictionary<string, object>();
        if (reg.ValueCount == 0) { return null; }
        ForeachRegKeys(reg, ref dic);
        return dic;
    }

    /// <summary>
    /// 获取子项(name,value)字典,没有则返回null
    /// </summary>
    /// <param name="reg">当前RegistryKey</param>
    /// <returns></returns>
    public static IDictionary<string, object> GetSubKeyValueDic(this RegistryKey reg)
    {
        var dic = new Dictionary<string, object>();
        if (reg.SubKeyCount == 0) { return null; }
        foreach (var item in reg.GetSubKeyNames())
        {
            //以只读方式检索子项
            var sonKey = reg.OpenSubKey(item);
            ForeachRegKeys(sonKey, ref dic);
        }
        return dic;
    }

    /// <summary>
    /// 遍历RegistryKey
    /// </summary>
    /// <param name="reg"></param>
    /// <param name="dic"></param>
    private static void ForeachRegKeys(RegistryKey reg, ref Dictionary<string, object> dic)
    {
        foreach (var name in reg.GetValueNames())
        {
            dic.Add(name, reg.GetValue(name));
        }
    }
    #endregion

    #region 添加
    /// <summary>
    /// 添加一个子项
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static RegistryKey AddSubItem(this RegistryKey reg, string name)
    {
        return reg.CreateSubKey(name);
    }

    /// <summary>
    /// 添加key-value,异常则RegistryKey对象返回null
    /// </summary>
    /// <param name="reg"></param>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static RegistryKey AddKeyValue(this RegistryKey reg, string key, object value)
    {
        reg.SetValue(key, value);
        return reg;
    }
    #endregion

    #region 修改
    /// <summary>
    /// 修改key-value,异常则RegistryKey对象返回null
    /// </summary>
    /// <param name="reg"></param>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static RegistryKey UpdateKeyValue(this RegistryKey reg, string key, object value)
    {
        return reg.AddKeyValue(key, value);
    }
    #endregion

    #region 删除
    /// <summary>
    /// 根据Key删除项
    /// </summary>
    /// <param name="reg"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static RegistryKey DeleteKeyValue(this RegistryKey reg, string key)
    {
        reg.DeleteValue(key, false);
        return reg;
    }

    /// <summary>
    /// 删除子项所有内容
    /// </summary>
    /// <param name="reg"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static RegistryKey ClearSubAll(this RegistryKey reg, string key)
    {
        reg.DeleteSubKeyTree(key, false);
        return reg;
    }
    #endregion
}

你可能感兴趣的:(弥补学生时代的遗憾~C#注册表情缘)