如何使用C#代码获取可用SQL Server列表?

时间:2012-05-28 08:09:28

标签: c# sql-server-2008

我创建了一个桌面应用程序。在应用程序启动时,我想在本地PC上显示所有可用SQL Server实例的列表,并允许选择要连接的SQL Server名称。

是否有获取本地PC上可用的所有SQL Server实例名称的列表?

非常感谢。

3 个答案:

答案 0 :(得分:14)

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"]);
      }
  }

答案 1 :(得分:3)

        //// 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()
                });

答案 2 :(得分:2)

尝试

SqlDataSourceEnumerator.Instance.GetDataSources()