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)

4

2 回答 2

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

配置HKEY_CURRENT_USER单元不包含名称以 . 开头的键HKEY_LOCAL_MACHINE。如果您尝试从本地计算机配置单元读取,则需要更新您的代码:

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

此外,如果Wow6432Node密钥不存在(也许您在 32 位操作系统上运行?),或者不包含名为 的密钥Shit,则该OpenSubKey方法将返回null.

于 2012-10-30T19:53:55.497 回答
0

我这样修复它:

首先,我检查了设置是否为空。如果设置为空,那么我首先创建子键。在此之后,我重新设置了设置变量,一切都很好。

settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
if (settings == null)
{
    Registry.CurrentUser.CreateSubKey("SOFTWARE\\Shit").Flush();
    settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
}
于 2012-10-30T20:03:27.053 回答