Get All Installed SQL Server Instances On Local Machine Using C#

This is a very short code snippet where I will explain how to list the SQL Server instances that are installed on your machine and on the network connected to your machine. By using SqlDataSourceEnumerator and EnumAvailableSqlServers, we can get SQL Server instances that are installed on your machine as well as on the network, connected.
 
For this, we need to import these classes.
  1. using System;  
  2. using System.Data;  
  3. using System.Data.Sql;  
  4. using Microsoft.Win32;  
  5. using Microsoft.SqlServer.Management.Smo;   
Using SqlDataSourceEnumerator Class
 
The SqlDataSourceEnumerator class allows you to get the instances of the SQL Server installed on the machine and also on the network the machine is connected to.
  1. private void GetDataSources()  
  2. {  
  3.     SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;  
  4.     DataTable table = instance.GetDataSources();  
  5.     string ServerName = Environment.MachineName;  
  6.     foreach (DataRow row in table.Rows)  
  7.     {  
  8.         Console.WriteLine (ServerName + "\\" + row["InstanceName"].ToString());  
  9.     }  

Using EnumAvailableSqlServers Class
 
First of all, you need to add a reference to the Microsoft.SqlServer.smo.dll file to your project which is available in NuGet Package Manager.
  1. private void GetDataSources()  
  2. {  
  3.     DataTable table = SmoApplication.EnumAvailableSqlServers(true);  
  4.     string ServerName = Environment.MachineName;  
  5.     foreach (DataRow row in table.Rows)  
  6.     {  
  7.         Console.WriteLine(ServerName + "\\" + row["InstanceName"].ToString());  
  8.     }  

EnumAvailableSqlServers and SqlDataSourceEnumerator will only find named instances if the SQL Server Browser services are running. If you want to get the SQL Server instance name on the current computer, you can read the information from the registry.
  1. private void GetDataSources2()  
  2. {  
  3.     string ServerName = Environment.MachineName;  
  4.     RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;  
  5.     using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))  
  6.     {  
  7.         RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"false);  
  8.         if (instanceKey != null)  
  9.         {  
  10.             foreach (var instanceName in instanceKey.GetValueNames())  
  11.             {  
  12.                 Console.WriteLine(ServerName + "\\" + instanceName);  
  13.             }  
  14.         }  
  15.     }  

These simple tips can help all readers. I hope you find this blog helpful.
 
Happy Coding!
Next Recommended Reading Count Instances Of The Class Using C#