C#Registry无法写入

时间:2016-01-09 16:38:09

标签: c# exception registry

当我尝试写入CurrentUser注册表中的现有子键时,抛出异常。如果注册表为null,则写入正常。例外是“无法写入注册表项”

//create subkey
RegistryKey lo1 = Registry.CurrentUser.OpenSubKey(KEY_NAME);
// If the RegistrySubKey doesn't exist -> (null)
if (lo1 == null)
{
    try
    {
    lo1 = Registry.CurrentUser.CreateSubKey(KEY_NAME);
    // Save the the current date
    lo1.SetValue(KEY_NAME, DateTime.UtcNow);
    }
    catch (Exception e)
    {
        //on error,
        return false;
    }
}

稍后,如果满足某些条件,我想覆盖该值。我尝试使用这一行并抛出异常

lo1.SetValue(KEY_NAME, DateTime.UtcNow);

1 个答案:

答案 0 :(得分:1)

尝试以下

Registry.CurrentUser.OpenSubKey(KEY_NAME,true)

键应该以可写方式打开。

如果不起作用,请尝试以下操作。

  var user = Environment.UserDomainName + "\\" + Environment.UserName;
  var rs = new RegistrySecurity();
  rs.AddAccessRule(new RegistryAccessRule(user,
    RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.WriteKey,
    InheritanceFlags.None,
    PropagationFlags.None,
    AccessControlType.Allow));

  var lo1 = Registry.CurrentUser.CreateSubKey(KEY_NAME, RegistryKeyPermissionCheck.Default, rs);