Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top