如何从连接字符串获取服务器名称(仅限没有SQL Server实例)

时间:2016-01-15 19:40:40

标签: c# sql-server connection-string

我想测试一个SQL Server是否存在tcp套接字(如果服务器不存在,它会更快)。

如果连接字符串是这样的:

name="DefaultConnection" 
connectionString="Data Source=COMPUTERNAME\SQLSERVERNAME;Initial Catalog=TestDb;Integrated Security=False;User ID=sa;Password=1234;MultipleActiveResultSets=True"/>

我想使用这种方法:

public bool CheckServerAvailablity(string sServerAddressOrName)
{
        try
        {
             string connectString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
            // Retrieve the DataSource property.    
            string sServerAddressOrName = builder.DataSource;
            int port = 1433;
            IPHostEntry ipHostEntry = Dns.GetHostEntry(sServerAddressOrName);
            IPAddress ipAddress = ipHostEntry.AddressList[0];

            TcpClient TcpClient = new TcpClient();
            TcpClient.Connect(ipAddress, port);
            TcpClient.Close();

            return true;
        }
        catch
        {
            return false;
        }
    } 

问题是:sServerAddressOrName = COMPUTERNAME\SQLSERVERNAME,但我只需要COMPUTERNAME

所以,问题是如何只获得COMPUTERNAME

提前致谢!

2 个答案:

答案 0 :(得分:4)

您可以使用Split()功能

string sServerAddressOrName = builder.DataSource.Split('\\')[0];

答案 1 :(得分:-1)

DataSourceSqlConnectionStringBuilder属性获取要连接的SQL Server实例的名称/网络地址。

在您的情况下,它是机器的主机名和SQL Server实例名称,以DataSource分隔。

如果你只是需要在这个特定场景下工作的东西,你可以访问\并在String myConnectionString = "Data Source=COMPUTERNAME\\SQLSERVERNAME;Initial Catalog=TestDb;Integrated Security=False;User ID=sa;Password=1234;MultipleActiveResultSets=True"; var builder = new SqlConnectionStringBuilder(myConnectionString); String hostname = builder.DataSource.Split(new Char[] { '\\' })[0]); 字符上拆分字符串,如下所示:

DataSource

尽管如此,上述方法并不完全通用,并且不适用于更复杂的var builder = new SqlConnectionStringBuilder(connectionString); Int32 length = builder.DataSource.LastIndexOf('\\'); Int32 start = builder.DataSource.LastIndexOf('\\', length - 1) + 1; if (start == length) { start = 0; } else { length -= start; } var hostname = builder.DataSource.Substring(start, length); 值。

Since you can't use \ in a SQL Server instance name,我们可以利用这些信息来制作略微更好的解决方案:

\\COMPUTERNAME\pipe\pipeName

但是,我应该补充一点,如果使用命名管道(COMPUTERNAME:1433),端口号({{1})指定数据源,即使解决方案也无法工作})或强制TCP参数(即tcp:COMPUTERNAME)。