Reputation: 603
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)
Upvotes: 2
Views: 3736
Reputation: 603
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);
}
Upvotes: 0
Reputation: 31198
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
.
Upvotes: 4