The following code returns the list of SQL Server names and the system names on which they are installed.

public static List GetSqlServerInstances()
{
DataTable dtSqlServerInstances;
List lstSqlServerInstances = new List();

SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
dtSqlServerInstances = instance.GetDataSources();
foreach (System.Data.DataRow drSqlServerInstance in dtSqlServerInstances.Rows)
lstSqlServerInstances.Add(drSqlServerInstance["ServerName"].ToString() + “\” + drSqlServerInstance["InstanceName"].ToString());
return lstSqlServerInstances;
}

This code will work too. Additionally along with the server name and instance name, it will return whether the instance is clustered or not and the SQL server version too.

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

if (factory.CanCreateDataSourceEnumerator)

{

DbDataSourceEnumerator dataSourceEnumerator = factory.CreateDataSourceEnumerator();

if (dataSourceEnumerator != null)

{

// Here is the list of SQL Servers

DataTable dt = dataSourceEnumerator.GetDataSources();

}

}

Advertisements