Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of available SQL Servers using C# Code?

I have created a desktop application. On application launch I want to display the list of all available SQL Server instances on the local PC, and allow to choose a SQL Server name to connect with.

Is there anyway to get the list of all SQL Server instance names that are available on the local PC?

Thanks a lot.

like image 394
Jameel Avatar asked May 28 '12 08:05

Jameel


1 Answers

string myServer = Environment.MachineName;

DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
for (int i = 0; i < servers.Rows.Count; i++)
{
    if (myServer == servers.Rows[i]["ServerName"].ToString()) ///// used to get the servers in the local machine////
     {
         if ((servers.Rows[i]["InstanceName"] as string) != null)
            CmbServerName.Items.Add(servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);
         else
            CmbServerName.Items.Add(servers.Rows[i]["ServerName"].ToString());
      }
  }
like image 95
Pranay Rana Avatar answered Sep 28 '22 05:09

Pranay Rana