2

I want to read from Registry and set some Values, but i keep getting NullReferenceExceptions.

public partial class Form1 : Form
{

    RegistryKey rkApp = null;
    RegistryKey settings = null;

    public Form1()
    {
        InitializeComponent();

        rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        settings = Registry.CurrentUser.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Shit", true);

        if (settings.GetValue("automove") != null)
        {
            automove = true;
            autostartToolStripMenuItem.Checked = true;
        }
    }
}

i deleted some unrelevant code in this example but this is my code... Any Ideas?

The error appears in line if (settings.GetValue("automove") != null)

Styler2go
  • 604
  • 2
  • 12
  • 32
  • what line is the exception thrown from (examine the `StackTrace` from the exception) – James Michael Hare Oct 30 '12 at 19:45
  • if (settings.GetValue("automove") != null) – Styler2go Oct 30 '12 at 19:49
  • `settings` isn't `null`? – danielQ Oct 30 '12 at 19:52
  • Then you know why you're getting a NullReferenceException - your actual question is why settings is null, yes? Context is extremely important for people to be able to answer you quickly and correctly. =) – J. Steen Oct 30 '12 at 19:55
  • why are you trying to open HKLM from HKCU? http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine.aspx Also check http://stackoverflow.com/questions/1074411/how-to-open-a-wow64-registry-key-from-a-64-bit-net-application – NoviceProgrammer Oct 30 '12 at 19:58

2 Answers2

4
Registry.CurrentUser.OpenSubKey("HKEY_LOCAL_MACHINE\\...

The HKEY_CURRENT_USER hive doesn't contain a key whose name starts with HKEY_LOCAL_MACHINE. If you're trying to read from the local machine hive, you'll need to update your code:

Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Shit", true)

Also, if either the Wow6432Node key doesn't exist (maybe you're running on a 32-bit OS?), or doesn't contain a key called Shit, then the OpenSubKey method will return null.

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
0

I fixed it this way:

First, i checked if settings is null. If settings is null then i create the SubKey first. After this, i re-set the settings variable and evrything is fine.

settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
if (settings == null)
{
    Registry.CurrentUser.CreateSubKey("SOFTWARE\\Shit").Flush();
    settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
}
Styler2go
  • 604
  • 2
  • 12
  • 32