How to solve System.UnauthorizedAccessException : "Cannot write to the registry key" error RRS feed

  • Question

  • 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!.
    Sunday, October 15, 2017 4:36 PM

All replies

  • Absent customization of security for a registry key in the HKLM hive, write access requires that code run with elevated privilege as an Administrator.
    Sunday, October 15, 2017 6:57 PM
  • And how do i do that please tell me?.

    Sunday, October 15, 2017 7:11 PM
  • And how do i do that please tell me?.

    Right click on the executable from Explorer and select "Run as Administrator".
    • Proposed as answer by Ashidacchi Monday, October 16, 2017 5:52 AM
    Sunday, October 15, 2017 8:03 PM
  • Hello Abdullah,

    You could run the program as "Administrator" level and it works well on my side.

     If your issues has been solved, you could close the thread by marking  as answer, This can be beneficial to other community members reading this thread.


    Neil Hu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Sunday, October 29, 2017 6:53 AM
  • And how do i do that please tell me?.

    You can use the .NET manifest.
    Sunday, October 29, 2017 2:39 PM
  • And to round out the possibilities, open an elevated command prompt and use it to run the program.

    Regardless of the method used, the answer remains the same -- your program must run with elevated privilege in order to write to HKLM.

    • Proposed as answer by Fei HuModerator Wednesday, November 1, 2017 8:35 AM
    Sunday, October 29, 2017 2:57 PM
  • I have a msi installer and i cant see the run as administrator option in my windows 7 machine(when i right click my msi installer)
    Friday, August 24, 2018 1:11 PM