在计算机本地或网络中获取具有sqlserver名称的servername

时间:2013-05-01 17:07:08

标签: c# winforms

DataTable table = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow server in table.Rows)
{
    cmbshowallsqlserver.Items.Add(server[table.Columns["ServerName"]].ToString());
}

此代码仅提供计算机名称。我想给我带有sqlserver名称的computername。 例如这段代码给我anfd-pc,但我需要例如anfd-pc \ sqlexpress或anfd-pc \ zarnegar

2 个答案:

答案 0 :(得分:3)

您从ServerName获得的表中的GetDataSources()列就是服务器名称。您还可以从InstanceName列中获取实例名称。其他可用选项See MSDN

所以你的代码会变成这样:

cmbshowallsqlserver.Items.Add(
    string.Format(@"{0}\{1}",
                  server[table.Columns["ServerName"]],
                  server[table.Columns["InstanceName"]])
);

答案 1 :(得分:0)

DataTable table = SqlDataSourceEnumerator.Instance.GetDataSources();

foreach (DataRow server in table.Rows)
{
    string servername = server[table.Columns["ServerName"]].ToString();

    // you can get that using the instanceName property 
    string instancename = server[table.Columns["InstanceName"].ToString();

    //and version property tells you the version of sql server i.e 2000, 2005, 2008 r2 etc
    string sqlversion = server[table.Columns["Version"].ToString();

    //to form the servername you can combine the server and instancenames as
    string sqlserverfullname = String.Format("{0}\{1}",servername, instancename);

    cmbshowallsqlserver.Items.Add(sqlserverfullname);
}