0

I'm trying to add a registry key (if it doesn't already exist) and have the following code:

RegistrySecurity rs = new RegistrySecurity();

rs.AddAccessRule(new RegistryAccessRule(Environment.UserDomainName + "\\" + Environment.UserName,
            RegistryRights.FullControl,
            InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow));

RegistryKey RK = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION");
if (RK != null)
{

}
else
{
    RegistryKey RK1 = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
    RK1.SetValue("TestValue1", "Test.exe", RegistryValueKind.DWord);
} 

The problem is that I get an UnauthorisedAccessException at the point at the CreateSubKey line.

Sounds to me like a permissions issue, but I thought the RegistrySecurity took care of it.

Does anyone know what the problem may be?

cosmarchy
  • 686
  • 3
  • 9
  • 21
  • You don't have permission to write to HKLM. Use HKCU. – SLaks Apr 13 '15 at 19:44
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Apr 13 '15 at 19:46
  • Ok, using HKCU no longer produces an exception however it also does not create the sub-key either!! – cosmarchy Apr 13 '15 at 20:07

1 Answers1

0

The AddAccessRule method isn't going to grant you write access permissions to the registry key if your user account doesn't already have write access to that part of the registry (otherwise any user could just grant themselves permissions to any part of the registry they wanted).

You will need to run your application under a user account that already has read/write permissions to that part of the registry for this to work. On my Windows 7 machine, that is the SYSTEM account and any user belonging to the Administrators group. The default permissions for those FeatureControl keys grant read access to standard users and deny write access.

The articles here and here describe how you can go about elevating your application so it has Administrator privileges and consequently write access to those registry keys.

Community
  • 1
  • 1
ScheuNZ
  • 911
  • 8
  • 19