This is just another SQL C# articles which let you learn how to make a list of names of SQL instance available on your Microsoft SQL Server using C# code.
This is made possible using Registry entries.
private IEnumerable<string> ListLocalSqlInstances(RegistryKey hive)
{
const string keyName = @"Software\Microsoft\Microsoft SQL Server";
const string valueName = "InstalledInstances";
const string defaultName = "MSSQLSERVER";
using (var key = hive.OpenSubKey(keyName, false))
{
if (key == null) return Enumerable.Empty<string>();
var value = key.GetValue(valueName) as string[];
if (value == null) return Enumerable.Empty<string>();
for (int index = 0; index < value.Length; index++)
{
if (string.Equals(value[index], defaultName, StringComparison.OrdinalIgnoreCase))
{
value[index] = ".";
}
else
{
value[index] = @".\" + value[index];
}
}
return value;
}
}
public IEnumerable<string> ListLocalSqlInstances()
{
if (Environment.Is64BitOperatingSystem)
{
using (var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
foreach (string item in ListLocalSqlInstances(hive))
{
yield return item;
}
}
using (var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
{
foreach (string item in ListLocalSqlInstances(hive))
{
yield return item;
}
}
}
else
{
foreach (string item in ListLocalSqlInstances(Registry.LocalMachine))
{
yield return item;
}
}
}
How to use the function
The function has two part, one with argument which dig for registry element another will extract the information.
txt_instance.ItemsSource = SqlHelper.ListLocalSqlInstances();
The a above line will serve the list of string ( instance names ) and serve as itemsource for a combo box control.