无法使用c# . net中的RegistryKey类设置注册表值

本文关键字:RegistryKey 设置 注册表 中的 net | 更新日期: 2023-09-27 18:07:51

我正在使用Visual c# 2010,并且在设置注册表项时遇到问题。我认为这是与我没有以管理员身份运行它的事实有关,但我已经尝试构建发布,然后右键单击exe并选择"以管理员身份运行",但无济于事。

我还尝试使用RegistryPermission类,这似乎没有任何区别。

代码如下:

RegistryKey rkey = Registry.LocalMachine;
// RegistryPermission f = new RegistryPermission(
//    RegistryPermissionAccess.Write | RegistryPermissionAccess.Read,
 //   @"HKEY_LOCAL_MACHINE'SOFTWARE'Company'Product");

/**********************/
/* set registry keys  */
/**********************/
RegistryKey wtaKey = rkey.OpenSubKey(@"SOFTWARE'Company'Product", true);
try
{
    wtaKey.SetValue("key1", 123);
    wtaKey.SetValue("key2", 567);
    wtaKey.SetValue("key3", textbox.Text);
    wtaKey.SetValue("key4", "some string");
}
catch (UnauthorizedAccessException ex)
{
    MessageBox.Show(ex.Message);
    return;
}

这给了我每次运行它时异常的错误消息,即使使用'以管理员身份运行'。有什么好办法吗?这看起来很奇怪,因为我的标准用户帐户允许我进入regedit并手动更改这些值,没有问题。

无法使用c# . net中的RegistryKey类设置注册表值

可以了

:

你应该使用CreateSubKey而不是OpenSubKey。

第二:

这不是您遇到的管理问题,相反,您只是需要在注册表路径的末尾添加另一个"'"。

 private void button1_Click(object sender, EventArgs e)
 {
     RegistryKey rkey = Registry.LocalMachine;
     RegistryPermission f = new RegistryPermission(
     RegistryPermissionAccess.Write | RegistryPermissionAccess.Read,
         @"HKEY_LOCAL_MACHINE'SOFTWARE'Company'Product");
     /**********************/
     /* set registry keys  */
     /**********************/
     RegistryKey wtaKey = rkey.CreateSubKey(@"SOFTWARE'Company'Product'");
     try
     {
         wtaKey.SetValue("key1", 123);
         wtaKey.SetValue("key2", 567);
         wtaKey.SetValue("key4", "some string");
     }
     catch (UnauthorizedAccessException ex)
     {
         MessageBox.Show(ex.Message);
         return;
     }
 }