用C#写的一个注册表操作类

该类实现了注册表读取、写入、删除、查找等功能。

实现代码:

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

namespace TagReceiver
{
    class RegistryHelper
    {
        /// <summary>
        /// 读取指定名称的注册表的值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetRegistryData(RegistryKey root, string subkey, string name) 
        { 
            string registData = ""; 
            RegistryKey myKey = root.OpenSubKey(subkey, true);
            if (myKey != null)
            {
                registData = myKey.GetValue(name).ToString();
            }

            return registData; 
        } 

        /// <summary>
        /// 向注册表中写数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tovalue"></param> 
        public void SetRegistryData(RegistryKey root, string subkey, string name, string value) 
        { 
            RegistryKey aimdir = root.CreateSubKey(subkey); 
            aimdir.SetValue(name, value); 
        } 

        /// <summary>
        /// 删除注册表中指定的注册表项
        /// </summary>
        /// <param name="name"></param>
        public void DeleteRegist(RegistryKey root, string subkey, string name) 
        { 
            string[] subkeyNames;
            RegistryKey myKey = root.OpenSubKey(subkey, true);
            subkeyNames = myKey.GetSubKeyNames();
            foreach (string aimKey in subkeyNames) 
            { 
                if(aimKey == name)
                    myKey.DeleteSubKeyTree(name); 
            } 
        } 

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsRegistryExist(RegistryKey root, string subkey, string name) 
        { 
            bool _exit = false; 
            string[] subkeyNames; 
            RegistryKey myKey = root.OpenSubKey(subkey, true);
            subkeyNames = myKey.GetSubKeyNames(); 
            foreach(string keyName in subkeyNames) 
            { 
                if(keyName == name) 
                { 
                    _exit = true; 
                    return _exit; 
                } 
            } 

            return _exit; 
        } 
    }
}

如何调用:

读注册表:

            RegistryHelper rh = new RegistryHelper();

            string portName = rh.GetRegistryData(Registry.LocalMachine, "SOFTWARE\\TagReceiver\\Params\\SerialPort", "PortName");
写注册表:

            RegistryHelper rh = new RegistryHelper();
            rh.SetRegistryData(Registry.LocalMachine, "SOFTWARE\\TagReceiver\\Params\\SerialPort", "PortName", portName);

所有代码在WinXP SP3+VS2010下测试通过。

posted on 2012-08-23 14:21  onedime  阅读(12197)  评论(2编辑  收藏  举报