注册表:是Microsoft Windows中的一个重要的数据库,此文章主要记录一下,如何对注册表进行增删改查。
查看注册表的命令:regedit或regedit.exe、regedt32或regedt32.exe
1.windows键加R键。
2.输入命令。
3.查看。
4.代码举例。
①引用:
using Microsoft.Win32;
②案例:
public class RegistryHelper
{
/// <summary>
/// 创建注册表项
/// </summary>
/// <returns></returns>
public static bool CreateSubKey()
{
try
{
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.CreateSubKey("SOFTWARE\\Test");
if (software != null) return true;
else return false;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 打开注册表项
/// </summary>
/// <returns></returns>
public static bool OpenSubKey()
{
try
{
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("SOFTWARE\\Test", true);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 删除注册表项
/// </summary>
/// <returns></returns>
public static bool DeleteSubKey()
{
try
{
RegistryKey key = Registry.LocalMachine;
key.DeleteSubKey("SOFTWARE\\Test", true);
key.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 键值的创建与修改[无则创建,有则修改]
/// </summary>
/// <returns></returns>
public static bool SetValue()
{
try
{
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("SOFTWARE\\Test", true);
software.SetValue("name", "DuanXuWen");
key.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 获取键对应的值
/// </summary>
/// <returns></returns>
public static string GetValue()
{
try
{
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("SOFTWARE\\Test");
string value = software.GetValue("name").ToString();
software.Close();
return value;
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 删除键值
/// </summary>
/// <returns></returns>
public static bool DeleteValue()
{
try
{
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Test", true);
delKey.DeleteValue("name");
delKey.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 注册表项是否存在
/// </summary>
/// <returns></returns>
private bool IsRegeditItemExist()
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE");
subkeyNames = software.GetSubKeyNames();
foreach (string keyName in subkeyNames)
{
if (keyName == "Test")
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
/// <summary>
/// 键是否存在
/// </summary>
/// <returns></returns>
private bool IsRegeditKeyExit()
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE\\Test");
subkeyNames = software.GetValueNames();
foreach (string keyName in subkeyNames)
{
if (keyName == "name")
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
}