C#在Registry Local Machine中创建值

以下代码对我不起作用:

public bool createRegistry() { if (!registryExists()) { Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\"); Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\xelo").SetValue("hostname", (string)hostname, Microsoft.Win32.RegistryValueKind.String); return true; } else { return updateRegistry(); } } 

例外:

System.UnauthorizedAccessException | “无法写入注册表项”

非管理员和非管理员管理员用户无权修改HKEY_LOCAL_MACHINE键。 以管理员身份运行程序。

即使是管理员,我也不认为你可以在LocalMachine上创建新的密钥。 确保你这样做

 Registry.LocalMachine.CreateSubKey(@"SOFTWARE\YourCompanyName\SomeNewKey"); 

并不是

 Registry.LocalMachine.CreateSubKey("SomeNewKey"); 

下面的代码在注册表中创建密钥。

 Microsoft.Win32.RegistryKey key; key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\Wow6432Node\\Names"); key.SetValue("Name", "Isabella"); key.Close(); 

那么你已经得到了你的答案 – 我猜你是在Vista或Windows 7(或Server 2008)上运行而且运行应用程序的进程/用户没有修改注册表的权限/权限。

所以它不是代码问题,而是系统管理员问题。 构建应用程序并以管理员身份运行,看看是否有效。

将Premission Check位设置为true …

 Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\", true); 

🙂