coolhand
coolhand

Reputation: 2061

C# Registry cannot be written to

I have an exception thrown when I try to write to an an existing sub-key within the CurrentUser registry. It writes fine if the registry is null. The exception is "Cannot write to registry key"

//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;
    }
}

Later, if certain conditions are met, I want to overwrite the value. I try using this line and have the exception thrown

lo1.SetValue(KEY_NAME, DateTime.UtcNow);

Upvotes: 0

Views: 210

Answers (1)

tchelidze
tchelidze

Reputation: 8318

Try following

Registry.CurrentUser.OpenSubKey(KEY_NAME,true)

key should be opened as writable.

If that does not works try following.

  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);

Upvotes: 1

Related Questions