C# Registry SetValue throws UnauthorizedAccessException

只谈情不闲聊 提交于 2019-12-01 16:19:34

in the var for your key

var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);

change to

var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree);  

One possible issue that I see with your code is that the Path variable is being set to a string that doesn't escape the \ characters. How about something like:

Path = @"S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System";

Have you tried setting the accessrule and permissions?

 string user = Environment.UserDomainName + "\\" + Environment.UserName
        RegistryAccessRule rule = new RegistryAccessRule(user,
        RegistryRights.FullControl,
        AccessControlType.Allow);        
        RegistrySecurity security = new RegistrySecurity();
        security.AddAccessRule(rule);
        var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
        key.SetAccessControl(security);

As a last ditch effort to figure out what was going on, I created a simple service to test this code that will run as the local system account. It's the highest privileges I could think of to try and run the code with. Running the code with these permissions worked.

Special thanks go out to 0_____0 and Charleh for pointing out the anti-virus as well. I checked the logs and it turns out it was trying to quarantine my changes. I guess even it won't stop the System user from making these changes though.

Special thanks go out to Sorceri as well for helping me research this so much.

In conclusion, if you're having intermittent, extremely odd behavior, check your virus scanner and permissions.

Only set grants to dword. You must to open Registry and at the last folder path, rigth click over it and set Grants, and select All Aplications and check Total Control. I hope to help you.

just Registry.SetValue(sub_key, key, value);

Example:

Registry.SetValue(
            @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
            "MyApp",
            Application.ExecutablePath);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!