C# NullReferenceException when reading a registry key
I'm getting a NullReferenceException error on some simple code for handling a button click event. I've still got just a bit of code to add at the very end to actually display the value from "TcpAddr" on the messagebox. This will allow you run the program but clicking the button causes it to throw the error.
Also: Is it better practice to move the actual query out of the click event and just make the click event handle MessageBox.Show()?
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace LiteSwitch
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey("SOFTWARE\\Altiris\\Client Service");
object CurrDS 开发者_JAVA技巧= RegKey.GetValue("TcpAddr"); //This line causes the NRE Error
MessageBox.Show("Current DS:");
}
}
}
If you are sure that the registry key actually exists (use Regedit.exe) then you've got a problem if you are running on the 64-bit version of Windows. A VS2010 project is forced to run in 32-bit mode by default, it sees another set of registry keys.
Project + Properties, Build tab, Platform Target = Any CPU. Repeat for the Release configuration.
My guess is that
RegKey = RegKey.OpenSubKey("SOFTWARE\\Altiris\\Client Service");
Is returning a null, probably because that key doesn't exist.
Verify the key exists and the provided reg path is correct.
According to the documentation for OpenSubKey()
, "If the specified subkey cannot be found, then null is returned." If a variable is null, calling a method on it will throw that exception.
"Is it better practice to move the actual query out of the click event and just make the click event handle MessageBox.Show()?"
If you take it out, it won't necessarily reflect the current value of the key if, for example, another program modifies it while your program is running. Depending on your program, this may be okay.
If it's throwing a NRE it's because it can't find the value, make sure it's spelled correctly or that the previous line isn't also returning null
.
精彩评论