无法写入C#注册表
本文关键字:注册表 | 更新日期: 2023-09-27 18:29:47
当我试图写入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);
尝试以下
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);