using Microsoft.Win32;
namespace BrilliantSightClient.Model.Helper;
public static class RegistryHelper
{
private const string BaseRegistryKey = @"SOFTWARE\Yueyang\BrilliantSight";
///
/// 向注册表写入字符串类型值
///
/// 存储的键名
/// 要写入的字符串值
public static void WriteString(string keyName, string value)
{
using (var key = Registry.CurrentUser.CreateSubKey(BaseRegistryKey))
{
key?.SetValue(keyName, value, RegistryValueKind.String);
}
}
///
/// 从注册表读取字符串类型值
///
/// 存储的键名
/// 读取到的字符串值,若不存在则返回 null
public static string ReadString(string keyName)
{
using (var key = Registry.CurrentUser.OpenSubKey(BaseRegistryKey))
{
if (key == null) return null;
return key.GetValue(keyName) as string;
}
}
///
/// 向注册表写入布尔类型值(以 0/1 方式)
///
public static void WriteBool(string keyName, bool value)
{
using (var key = Registry.CurrentUser.CreateSubKey(BaseRegistryKey))
{
key?.SetValue(keyName, value ? 1 : 0, RegistryValueKind.DWord);
}
}
///
/// 从注册表读取布尔类型值(从 0/1 转换)
///
public static bool ReadBool(string keyName, bool defaultValue = false)
{
using (var key = Registry.CurrentUser.OpenSubKey(BaseRegistryKey))
{
if (key == null) return defaultValue;
object regValue = key.GetValue(keyName);
if (regValue == null) return defaultValue;
int intVal;
if (int.TryParse(regValue.ToString(), out intVal))
{
return intVal != 0; // 1->true, 0->false
}
return defaultValue;
}
}
///
/// 删除某个键值
///
/// 要删除的键名
public static void DeleteKey(string keyName)
{
using (var key = Registry.CurrentUser.OpenSubKey(BaseRegistryKey, writable: true))
{
if (key != null)
{
key.DeleteValue(keyName, throwOnMissingValue: false);
}
}
}
}