How to get list of available SQL Servers using C#

2020-05-20 23:57发布

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.

3条回答
乱世女痞
2楼-- · 2020-05-21 00:40
        //// Retrieve the enumerator instance, and then retrieve the data sources.
        SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
        DataTable dtDatabaseSources = instance.GetDataSources();

        //// Populate the data sources into DropDownList.            
        foreach (DataRow row in dtDatabaseSources.Rows)
            if (!string.IsNullOrWhiteSpace(row["InstanceName"].ToString()))
                Model.DatabaseDataSourceNameList.Add(new ExportWizardChooseDestinationModel
                {
                    DatabaseDataSourceListItem = row["ServerName"].ToString()
                        + "\\" + row["InstanceName"].ToString()
                });
查看更多
够拽才男人
3楼-- · 2020-05-21 00:50
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());
      }
  }
查看更多
可以哭但决不认输i
4楼-- · 2020-05-21 00:52

try

SqlDataSourceEnumerator.Instance.GetDataSources()
查看更多
登录 后发表回答