[C#, Windows]レジストリの読み書き操作

Microsoft.Win32.RegistryKeyインスタンスを使用してレジストリの読み書きをすることができる。

public static T GetLocalMachineRegistryValue<T>(string key, string name)
{
  using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key, false))
  {
    if (registryKey != null)
    {
      object value = registryKey.GetValue(name);
      return value is T ? (T)value : default(T);
    }
    else
    {
      return default(T);
    }
  }
}

public static bool SetLocalMachineRegistryValue<T>(string subkey, string name, T value)
{
  using (RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(subkey))
  {
    if (registryKey != null)
    {
      registryKey.SetValue(name, value);
      return true;
    }
    else
    {
      return false;
    }
  }
}

public static bool DeleteLocalMachineRegistryValue(string subkey, string name)
{
  using (RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(subkey))
  {
    if (registryKey != null)
    {
      registryKey.DeleteValue(name);
      return true;
    }
    else
    {
      return false;
    }
  }
}

static void Main(string[] args)
{
  string subkey = @"SOFTWARE\MySoftware\MyRegistryKeyName\Sample";
  string name = "ValueName";

  if (SetLocalMachineRegistryValue(subkey, name, 123))
  {
    Debug.WriteLine(
      GetLocalMachineRegistryValue<int>(subkey, name)); // print "123"

    DeleteLocalMachineRegistryValue(subkey, name);
    Debug.WriteLine(
      GetLocalMachineRegistryValue<int>(subkey, name)); // print "0"
  }
}
Share
関連記事