Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Access denied when creating registry key

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

HKEY_LOCAL_MACHINESOFTWAREMyCompanyMyProgram

Here is the code:

RegistryKey reg;
reg = Registry.LocalMachine.CreateSubKey(@"SOFTWAREMyCompanyMyProgram");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...