修改注册表项值

Har*_*mar 33 .net c# registry winforms

我有一个以下的注册表路径

HKEY_LOCAL_MACHINE\SOFTWARE\COMPANY\COMPFOLDER
Run Code Online (Sandbox Code Playgroud)

在内部COMPFOLDER,我有一个名为"Deno"的字符串值,其值为0.我希望每当执行代码时,通过代码将其值更改为1.谁能帮我?

Jon*_*tas 60

已经有一段时间我做了hack,但这样的事情可以起作用:

RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Company\\Compfolder", true);
if(myKey != null)    {
   myKey.SetValue("Deno", "1", RegistryValueKind.String);
   myKey.Close();
}
Run Code Online (Sandbox Code Playgroud)

  • `myKey` 应该位于 `using` 语句中。请参阅[“RegistryKey”的备注](https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey?view=netframework-4.8#remarks) (3认同)

ele*_*bah 15

  using (RegistryKey key = regKeyRoot.OpenSubKey(KeyName, true)) //must dispose key or use "using" keyword
    {
        if (key != null)  //must check for null key
        {
            key.SetValue(attribute, value);
        }
    }
Run Code Online (Sandbox Code Playgroud)