Access denied when creating registry key in C#

孤街浪徒 提交于 2019-12-03 22:10:30

问题


I am trying to create a registry key at following location but I am getting access denied error:

HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MyProgram

Here is the code:

RegistryKey reg;
reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MyCompany\MyProgram");

回答1:


You are most likely using User Account Control (UAC). This means that even if you are an administrator your access token doesn't have the necessary privileges to do things like creating registry keys in HKEY_LOCAL_MACHINE.

However, by going through a UAC prompt you can elevate your privileges.

Regedit includes a UAC manifest that will raise the prompt before it is executed ensuring that it can perform the actions it needs to be able to do. You can also right-click on an executable or shortcut and select Run as administrator.

So essentially you have three options:

  • Turn off UAC
  • Use Run as administrator
  • Include a UAC manifest in your executable

The first solution is less secure and the last solution is the most elegant (but also the one that actually requires some effort).




回答2:


You need to run your application under an account that has sufficient privileges to write to the registry at the specified location. Usually the HKEY_LOCAL_MACHINE branch is reserved for power users because it contains machine global settings.




回答3:


I tried below syntax:

SETX /S [Machine Name] [Variable] [Value] /M

I am not sure why but in Windows 7, if you specify machine name on which you are adding system variable, even for local machine then it works.



来源:https://stackoverflow.com/questions/10151771/access-denied-when-creating-registry-key-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!