Does someone knows how to extract machine name from SQL connection string? For example for following connection strings, when ran app/script on the machine "ighost", which has ip address 190.190.200.100:

"Server=ighost;Database=myDataBase;User Id=myUsername;Password=myPassword;"
"Server=(local);Database=myDataBase;User Id=myUsername;Password=myPassword;"
"Server=.\SqlExpress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
"Server=190.190.200.100,1433;Database=myDataBase;User Id=myUsername;Password=myPassword;"

I would like to get the as the result, just machine name:

ighost

This i not a duplicate of question above since I'm not asking how to parse connection string, but how to find server machine name even if connection string server property contains such value as (local), localhost, ipaddress, dot.

有帮助吗?

解决方案

If those connection strings refer to the same server, the only way for reliably find out the machine name is to connect to the server and run the following command:

select @@SERVERNAME

Sample code:

using (var cn = new SqlConnection(yourConnectionString))
{
    cn.Open();

    using (var cmd = new SqlCommand("Select @@SERVERNAME", cn))
    {
        Console.WriteLine(cmd.ExecuteScalar());
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top