How to get SQL Server Instance using Registry

Hi all, today I am going to show a simple code snippets on how to retrieve SQL server name/Instance with machine name using registry.

Step 1: Add reference “ using Microsoft.Win32”.

Step 2: create a form and add controls like label, combo box, button.

Step 3: write code for SQL Instance on button_click event.

  1. private void button1_Click(object sender, EventArgs e)   
  2. {  
  3.     RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;  
  4.     using(RegistryKey registrtKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))   
  5.     {  
  6.         RegistryKey instanceKey = registrtKey.OpenSubKey(@  
  7.         "SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"false);  
  8.         if (instanceKey != null)   
  9.         {  
  10.             foreach(var instanceName in instanceKey.GetValueNames())   
  11.             {  
  12.                 cmbSQLInstance.Items.Add(Environment.MachineName + "\\" + instanceName);  
  13.             }  
  14.         }  
  15.     }  
  16. }  

Step 4: Execute the program and get the result when click on button.