//RegistryAccess注册表访问类

using System;
using System.Reflection;
using Microsoft.Win32;

namespace WindowsFormsApplication1
{
   /// <summary>
   /// 访问注册表
   /// </summary>
  public class RegistryAccess
   {
      private RegistryKey _Software;
      private RegistryKey _Company;
      private RegistryKey _Product;
      public  RegistryAccess():this(((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),typeof(AssemblyCompanyAttribute),true )).Company,
          ((AssemblyProductAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),typeof(AssemblyProductAttribute),true )).Product)
      {

       }

       public RegistryAccess(string CompanyName, string ProductName)
      {
          _Software = Registry.LocalMachine.OpenSubKey(“Software”);
          _Company = _Software.OpenSubKey(CompanyName);
          if (null == _Company)
          {
              _Company = Registry.LocalMachine.CreateSubKey(“Software\” + CompanyName);

           }
          _Product = _Company.OpenSubKey(ProductName, true);
          if (null == _Product)
          {
              _Product=Registry.LocalMachine.CreateSubKey(string.Format (“Software\\{0}\\{1}”,CompanyName,ProductName ));
          }
      }
       /// <summary>
      /// 写注册表
      /// </summary>
      /// <param name=”ValueName”></param>
      /// <param name=”Value”></param>
      public void WriteRegistryValue(string ValueName, string Value)
      {
          _Product.SetValue(ValueName, Value);
      }
       /// <summary>
      /// 读注册表
      /// </summary>
      /// <param name=”ValueName”></param>
      /// <returns></returns>
      public string ReadRegistryValue(string ValueName)
      {
          return (string)_Product.GetValue(ValueName);
      }
          

    }
}

//测试读写注册表

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

        private void Form1_Load(object sender, EventArgs e)
       {
           SetText();   
       }
       private void SetText()
       {
           //从注册表加载信息
           RegistryAccess ra = new RegistryAccess();
           txtDepartment.Text = ra.ReadRegistryValue(“Department”);
           txtName.Text = ra.ReadRegistryValue(“Name”);
           txtPosition.Text = ra.ReadRegistryValue(“Position”);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
       {
           //关闭时往注册表写入信息
           RegistryAccess ra = new RegistryAccess();
           ra.WriteRegistryValue(“Department”, txtDepartment.Text);
           ra.WriteRegistryValue(“Name”, txtName.Text);
           ra.WriteRegistryValue(“Position”, txtPosition.Text);
        }

    }
}