使用.GetValueNames()方法的空引用异常

tom*_*ulk 3 .net c# registry

我试图在一台机器上获取SQL的所有实例名称,所有值都保存在一个regkey这里是我的代码,但我一直得到一个空引用异常.

private void RegLoop()
{
     RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL")
      foreach (var v in key.GetValueNames())
      {
         MessageBox.Show("{0}", v);
      }
}
Run Code Online (Sandbox Code Playgroud)

rid*_*rid 6

如果您收到该异常,则表示key包含null值.因此,该OpenSubKey()方法没有返回任何内容,可能是因为找不到您正在搜索的内容.