【问题标题】:NullReferenceException at RegistryKeyRegistryKey 处的 NullReferenceException
【发布时间】:2012-10-30 19:44:54
【问题描述】:

我想从注册表中读取并设置一些值,但我不断收到 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;
        }
    }
}

我在这个例子中删除了一些不相关的代码,但这是我的代码......有什么想法吗?

如果(settings.GetValue("automove") != null),则错误出现在行中

【问题讨论】:

  • 从哪一行抛出异常(检查异常中的StackTrace
  • if (settings.GetValue("automove") != null)
  • settings 不是null
  • 那么您知道为什么会收到 NullReferenceException - 您的实际问题是为什么设置为空,是吗?上下文对于人们能够快速正确地回答您非常重要。 =)
  • 你为什么要从 HKCU 打开 HKLM? msdn.microsoft.com/en-us/library/… 还要检查stackoverflow.com/questions/1074411/…

标签: c#


【解决方案1】:
Registry.CurrentUser.OpenSubKey("HKEY_LOCAL_MACHINE\\...

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

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

另外,如果 Wow6432Node 键不存在(也许您在 32 位操作系统上运行?),或者不包含名为 Shit 的键,那么 OpenSubKey 方法将返回null

【讨论】:

    【解决方案2】:

    我是这样解决的:

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

    settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
    if (settings == null)
    {
        Registry.CurrentUser.CreateSubKey("SOFTWARE\\Shit").Flush();
        settings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shit", true);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2012-12-07
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多