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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10781334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:14:36  来源:igfitidea点击:

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

c#sql-server-2008

提问by Jameel

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.

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

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

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

Thanks a lot.

非常感谢。

采纳答案by Pranay Rana

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

回答by Karthik

try

尝试

SqlDataSourceEnumerator.Instance.GetDataSources()

回答by Rashad Annara

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