0

I am trying to get all the SQL Instances installed on a local machine with the help of following code:

RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
string[] instances = (string[])rk.GetValue("InstalledInstances");

if (instances.Length > 0)    //Error
{
    foreach (string instance in instances)
    {
        MessageBox.Show(instance);
    }
}

It is giving the following exception:

Object reference not set to an instance of an object.

I've manually checked the 'Registry-Editor' and the specified keys exist, also there are two SQL Instances on my system.

Now please tell me why it is not accessing the required key value?

Kevin Aenmey
  • 13,259
  • 5
  • 46
  • 45
Muhammad Ali
  • 139
  • 1
  • 1
  • 6

2 Answers2

0

This line could be the issue string[] instances = (string[])rk.GetValue("InstalledInstances");

Because RegistryKey.GetValue Method (String) returns a object and you are casting that in to string[]

before casting it to string[] you should check if the returned value is not null

HatSoft
  • 11,077
  • 3
  • 28
  • 43
  • I don't think this answer is correct because if GetValue returned null then the cast to string[] would cause an error, since you can't cast a null value into a string array. His error seems to occur after this though, which tells me its not returning null and its successfully casting to a string array. – Icemanind Jul 06 '12 at 01:04
0

I ran your code on my 64-bit machine. It worked fine. Make sure you platform is set to AnyCPU or x64 but not x86

enter image description here

Harvey Kwok
  • 11,713
  • 6
  • 37
  • 59