C# 我的注册表操作类

时间:2023-03-08 18:42:36
C# 我的注册表操作类
 using System;
using System.Collections.Generic;
using System.Text; using Microsoft.Win32;
using System.Collections; namespace War3Screen
{
/// <summary>
/// 注册表操作类--kongfl888 2013
///
/// </summary>
class RegOperator
{ /// <summary>
/// 获取某键下的某键值
/// </summary>
/// <param name="_registrykey">注册表基项如 Registry.CurrentUser</param>
/// <param name="mainKeystr">项的注册表键path</param>
/// <param name="name"></param>
/// <returns></returns>
public static string Getkey(RegistryKey _registrykey, string mainKeystr,string name)
{
string valueStr = string.Empty; try
{ RegistryKey regKey = _registrykey;
RegistryKey mainKey = regKey.OpenSubKey(mainKeystr); valueStr = mainKey.GetValue(name).ToString();
}
catch { }
return valueStr; } /// <summary>
/// 设置和修改某键值
/// </summary>
/// <param name="_registrykey">注册表基项如 Registry.CurrentUser</param>
/// <param name="mainKeystr">项的注册表键path</param>
/// <param name="name">项名</param>
/// <param name="valueStr">项值</param>
/// <returns></returns>
public static bool Setkey(RegistryKey _registrykey, string mainKeystr, string name, string valueStr)
{
bool sc = false;
try
{
RegistryKey regKey = _registrykey;
RegistryKey mainKey = regKey.OpenSubKey(mainKeystr, true);
mainKey.SetValue(name, valueStr, RegistryValueKind.DWord); sc = true;
}
catch { sc = false; }
return sc;
} /// <summary>
/// 新建子键
/// </summary>
/// <param name="regKey">注册表基项如 Registry.CurrentUser</param>
/// <param name="SubKeyPath">子键路径</param>
/// <param name="SubKey">子键名</param>
/// <param name="keyValue">子键值</param>
public static bool Createkey(RegistryKey regKey, string SubKeyPath, string SubKey, string valueName, string keyValue, RegistryValueKind valueKind)
{
try
{
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
//添加子键和值
RegistryKey subkey = optionKey.CreateSubKey(SubKey);
subkey.SetValue(valueName, keyValue, valueKind);
return true;
}
catch
{
return false;
throw;
} } /// <summary>
/// 重载Createkey
/// </summary>
/// <param name="regKey"></param>
/// <param name="SubKeyPath"></param>
/// <param name="SubKey"></param>
public static bool Createkey(RegistryKey regKey, string SubKeyPath, string SubKey)
{
try
{
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
optionKey.CreateSubKey(SubKey);
return true;
}
catch
{
return false;
throw; } } /// <summary>
/// 删除子键
/// </summary>
/// <param name="regKey">注册表基项如 Registry.CurrentUser</param>
/// <param name="SubKeyPath">子键路径</param>
/// <param name="SubKey">子键名</param>
public static bool DelKey(RegistryKey regKey, string SubKeyPath, string SubKey)
{
try
{
//打开注册表 RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); string[] subKeys = optionKey.GetSubKeyNames(); foreach (string akey in subKeys)
{
if (akey == SubKey)
{
optionKey.DeleteSubKeyTree(SubKey);
return true;
}
}
return false; }
catch
{
return false;
throw;
}
} }
}