EnumAvailableSqlServers
and
SqlDataSourceEnumerator
will only find named instances if the SQL Server Browser services is running.
ManagedComputer
will only find servers registered in SQL Server Management Studio.
If you're just looking for servers on the current computer, you can read the information from the registry. The key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
has a value called
InstalledInstances
which contains the name of the SQL Server instances installed on the local computer:
public static class SqlHelper
{
public static 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;
}
}
}
private static 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;
}
}
}