Cannot write a new key to HKCU_Software (Visual C#)

  • Thread starter Robert G. Blois, Jr.
  • Start date
R

Robert G. Blois, Jr.

I am attempting to create a new key under HKCU_Software, and am receiving a
System.UnauthorizedAccessException. I am testing with Administrative
rights, and have no problem writing the key directly to HKCU. I cannot
figure out why I get this message in "Software", but not in the HKCU root.

This is my first time working with the registry, and this is just test code,
before I actually apply any of this to any kind of serious code, so certain
elements may be missing, such as comments, error checking, etc. However,
because this is my first time working with the registry, any comments in
these areas are welcome.

Thank you in advance for any help.
private void btnCreateKey_Click(object sender, System.EventArgs e)

{

//string test;

//RegistryKey reg = Registry.CurrentUser;

using(RegistryKey reg = Microsoft.Win32.Registry.CurrentUser)

{

try

{

//test = key.OpenSubKey("Software");

RegistryKey key = reg.OpenSubKey("Software");

//RegistryKey key = reg;

if(key != null)

{

MessageBox.Show(key.ToString(), "Key", MessageBoxButtons.OK,
MessageBoxIcon.Information);

key.CreateSubKey("MyTestKey");

}

else

MessageBox.Show("Unable to open key", "Error",
MessageBoxButtons.OK,

MessageBoxIcon.Exclamation);

}

catch(System.UnauthorizedAccessException)

{

MessageBox.Show("Sorry, but you don't have the permissions",
"Security Error", MessageBoxButtons.OK,

MessageBoxIcon.Exclamation);

}
 
M

Mattias Sjögren

Robert,
RegistryKey key = reg.OpenSubKey("Software");

This opens the key in read-only mode. For write access you should use

RegistryKey key = reg.OpenSubKey("Software", true);



Mattias
 
R

Robert G. Blois, Jr.

Thanks for the help. That was the problem.

Mattias Sjögren said:
Robert,


This opens the key in read-only mode. For write access you should use

RegistryKey key = reg.OpenSubKey("Software", true);



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top