註冊表:是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;
}
}