Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create Values in Registry Local Machine

Tags:

c#

registry

The following code 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();
    }
}

Exception:

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

like image 954
Angel.King.47 Avatar asked Apr 27 '10 17:04

Angel.King.47


3 Answers

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

like image 95
Kyle Alons Avatar answered Sep 29 '22 23:09

Kyle Alons


Below code to create key in the registry.

Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\Wow6432Node\\Names");
key.SetValue("Name", "Isabella");
key.Close();
like image 28
Dinesh Haraveer Avatar answered Sep 30 '22 01:09

Dinesh Haraveer


Even when admin I don't think you can create new keys off LocalMachine. Make sure that you do

Registry.LocalMachine.CreateSubKey(@"SOFTWARE\YourCompanyName\SomeNewKey");

and not

Registry.LocalMachine.CreateSubKey("SomeNewKey");
like image 29
nothingisnecessary Avatar answered Sep 29 '22 23:09

nothingisnecessary