tags:

views:

477

answers:

2

This is not working for me:

public bool createRegistry()
{
    if (!registryExists())
    {
        Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\");

        Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\xelo").SetValue("hostname", (string)hostname, Microsoft.Win32.RegistryValueKind.String);


        return true;
    }
    else
    {
        return updateRegistry();
    }

}

The exception error is to do with Not Authorized to do this. Any Help would be apreaciated

Exeption: System.UnauthorizedAccessException | "Cannot write to the registry key"

For the working answer read the comment on the accepted Solution

+3  A: 

Non-admin and unelevated admin users don't have rights to modify the HKEY_LOCAL_MACHINE key. Run the program 'as administrator'.

Kyle Alons
I am an admin, and running as admin gives me the same error
Shahmir Javaid
Check the permissions of the key in regedit.
Segfault
Try passing true to the 2nd parameter of the OpenSubKey call or using the return value of CreateSubKey. http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.opensubkey.aspx http://msdn.microsoft.com/en-us/library/ad51f2dx%28v=VS.100%29.aspx
Kyle Alons
Thanks Kyle, you have to do OpenSubKey("KeyName", true) Where the true means writable :D, Edit your answer to include that
Shahmir Javaid
@segfault, Did that same problem, need write access on the function
Shahmir Javaid
A: 

Well you've got your answer already - I'm guessing you're running on Vista or Windows 7 (or Server 2008) and the process/user running the app doesn't have rights/permission to modify the registry.

So its not a code problem as such but a systems admin one. Build the app and run as administrator and see if that works.

Murph
same error even as admin
Shahmir Javaid