Problem solve Get help with specific problems with your technologies, process and projects.

Trying to access a registry key using C# code, but getting an error

I tried to access the registry key LocalMachine/Software in C# using the code:

RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software",true);

But I am getting the following error:

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Requested registry access is not allowed.

Stack Trace:

[SecurityException: Requested registry access is not allowed.]
   Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable) +473
   EncryptionTestApp.Test.Button1_Click(Object sender, EventArgs e) in 
   System.Web.UI.WebControls.Button.OnClick(EventArgs e)

ackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,
String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   System.Web.UI.Page.ProcessRequest(HttpContext context)
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 
completedSynchronously) +87

Please help!
The first quick hack is to run regedit and try to open the desired key. This way you discard the possiblity that your Windows user lacks the permission. Next, try the following:

new System.Security.Permissions.RegistryPermission(
 // Access your key.

This tries to increase your assembly permissions with regards to the registry access (provided you have permissions to do that in the first place). The Assert..try..finally..Revert pattern must always be followed, to ensure you undo any security changes you make.

If this doesn't work, try signing your assembly. You can do this by first running the following command from the VS .NET command prompt:

sn –k mykey.snk

Then add the following attribute to your AssemblyInfo.cs file:

[assembly: AssemblyKeyFile(@"C:mykey.snk")]

If that doesn't work, you're probably on a corporate network where registry access is denied by enterprise .NET policy, in which case you should consult the appropriate administrator.

Dig Deeper on C# programming language

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.