代码如下:
using System.Windows.Forms;
using Microsoft.Win32;
namespace RegeditManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//创建并写入
private void button1_Click(object sender, EventArgs e)
{
RegistryKey key = Registry.LocalMachine;
try
{
RegistryKey software = key.CreateSubKey("software\LabManager");
software = key.OpenSubKey("software\LabManager", true);
software.SetValue("Address", @"C:Program Files实验室管理系统dbcom.xml");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
key.Close();
}
}
//读取
private void button2_Click(object sender, EventArgs e)
{
string info = string.Empty;
RegistryKey key=Registry.LocalMachine;
try
{
key = key.OpenSubKey("software\LabManager");
if (IsRegeditKeyExit("software\LabManager", "Address"))
{
info = key.GetValue("Address").ToString();
MessageBox.Show("注册表里的信息为:" + info);
}
else
{
MessageBox.Show("键值Address不存在;");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
key.Close();
}
}
//删除
private void button3_Click(object sender, EventArgs e)
{
RegistryKey key = Registry.LocalMachine;
try
{
key = key.OpenSubKey("software\LabManager",true);
if (IsRegeditKeyExit("software\LabManager", "Address"))
{
key.DeleteValue("Address");
MessageBox.Show("删除成功");
}
else
{
MessageBox.Show("键值Address不存在;");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
key.Close();
}
}
/// summary
/// 判断键值是否存在
/// /summary
/// param name="RegistryStr"注册表项/param
/// param name="KeyStr"键值/param
/// returns/returns
private bool IsRegeditKeyExit(string RegistryStr,string KeyStr)
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey(RegistryStr);
subkeyNames = software.GetValueNames();
foreach (string keyName in subkeyNames)
{
if (keyName == KeyStr) //判断键值的名称
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
/// summary
/// 判断注册表项是否存在
/// /summary
/// param name="RegistryName"例如:SOFTWARE/param
/// param name="ValueStr"例如:LabManager/param
/// returns/returns
private bool IsRegeditItemExist(string RegistryName,string ValueStr)
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey(RegistryName);
subkeyNames = software.GetSubKeyNames();
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)//取得该项下所有子项的名称的序列,并传递给预定的数组中
foreach (string keyName in subkeyNames) //遍历整个数组
{
if (keyName == ValueStr) //判断子项的名称
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
}
}