tags:

views:

287

answers:

2

I am setting a registry setting and I can do so if the value is in [HKEY_CURRENT_USER] but if the value is in [HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\9.0\ethan] then I get the following error:

ex {"Cannot write to the registry key."} System.Exception {System.UnauthorizedAccessException}

does anyone know what might be wrong? See code below:

private string setRegKey(string machinename)
    {
        try
        {
            RegistryKey regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.CurrentUser, machinename).OpenSubKey("Software").OpenSubKey("Adobe").OpenSubKey("Acrobat Reader").OpenSubKey("9.0").OpenSubKey("ethan");
            regKey.SetValue("Test", 1);
            regKey.Close();
            return "Success";
        }
        catch (Exception ex)
        {
            return "Error: " + ex.ToString();
        }
    }
A: 

Running regedt32.exe from the run box will open a version of regedit that allows you to view the permissions set on each registry key. You can use this to determine what permissions you need to edit the key. The next step would be to ensure that the account the application runs under has the appropriate permissions. If running the app with User Access Control enabled, it may be neccesary to launch it by holding shift while right clicking the exe, and selecting the 'Run as administrator' option. (This is what is meant by elevating an app)

Hannes Nel
A: 

Are you really trying to change settings on a remote machine? I suppose this might work if the user is a domain user.

In any case, one thing to be aware of is that each time you call 'OpenSubKey' you get a new instance of a RegistyKey object, and each one needs to be disposed. Otherwise you'll start to leak registry handles due to a finalization bug in the framework (this may have been fixed, but I disgress).

Also, it's not necessary to open each node of the key separately (unless this has to do with the remotely opened keys?). I'd suggest changing the code inside the try block to the following:

using ( RegistryKey remoteUserKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.CurrentUser, machinename) )
using ( RegistryKey remoteKey = remoteUserKey.OpenSubKey(@"Software\Adobe\Acrobat Reader\9.0\ethan") )
{
    remoteKey.SetValue("Test", 1);
    return "Success";
}

If you don't need to change this remotely, remove the first two lines and use this instead:

using ( RegistryKey key = Registry.LocalUser.OpenSubKey(@"Software\Adobe\Acrobat Reader\9.0\ethan") )
Kevin Pullin