且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决System.UnauthorizedAccessException:“无法写入注册表项”错误

更新时间:2022-10-29 14:55:00

如果HKLM配置单元中的注册表项没有自定义安全性,则写访问权限要求该代码作为管理员以提升的权限运行。


public void GetReqKey()
        {
            RegistryKey OEMBg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\LogonUI\\Background",true);
            if(OEMBg != null)
            {
                OEMBg.SetValue("OEMBackground",1,RegistryValueKind.DWord); --<Here the error is reported.
            }
        }

I cannot understand what is wrong with the following script. I have searched thousands of blogs but still cannot find the answer to it.It always throws an exception called "System.UnauthorizedAccessException: 'Cannot write to the registry key.'" .If someone would help me I would be very thankful!.

Absent customization of security for a registry key in the HKLM hive, write access requires that code run with elevated privilege as an Administrator.