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

后端 未结 3 1870
盖世英雄少女心
盖世英雄少女心 2021-02-02 01:01

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 na

3条回答
  •  离开以前
    2021-02-02 01:32

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

提交回复
热议问题