Mat Rat
Mat Rat

Reputation: 125

Get default SQL Server Instance On Local Machine Using C#

There is way to check which instance is Main/Default.

I use this

 private void GetDataSources2()  
 {  
     string ServerName = Environment.MachineName;  

     RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;  

     using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))  
     {  
         RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);  

         if (instanceKey != null)  
         {  
             foreach (var instanceName in instanceKey.GetValueNames())  
             {  
                 Console.WriteLine(ServerName + "\\" + instanceName);  
             }  
         }  
     }  
 } 

To find all instance. After it I check whether the database exists on any instance. If not I want to create it on main instance.

Upvotes: 1

Views: 673

Answers (1)

Iliar Turdushev
Iliar Turdushev

Reputation: 5213

According to MSDN default intance name is MSSQLSERVER:

The default instance name is MSSQLSERVER; it does not require a client to specify the name of the instance to make a connection.

Therefore to define if an instance is default it is necessary to check if the name of the instance is MSSQLSERVER.

Here are changes that can be made to your code to define if an instance is default:

private void GetDataSources2()
{
    string ServerName = Environment.MachineName;

    RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;

    using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
    {
        RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);

        if (instanceKey != null)
        {
            foreach (var instanceName in instanceKey.GetValueNames())
            {
                if (instanceName == "MSSQLSERVER")
                    // To reference default instance we should use name "ServerName".
                    Console.WriteLine(ServerName);
                else
                    // To reference non default instances we should use name "ServerName\InstanceName".
                    Console.WriteLine(ServerName + "\\" + instanceName);
            }
        }
    }
}

Upvotes: 2

Related Questions