SqlConnection - remote or local connection?
The easiest way I know of is to check the connection string directly to see if it contains the words localhost, 127.0.0.1, (localhost), "." or the name of the local machine. Check where to start as theirs might be a local named Sql instance.
You can use the System.Environment library to retrieve the current computer name. You can also use the ConnectionBuilder library in .Net to retrieve data without using full string parsing. Details on this can be found here
a source to share
You can get the connection string from objjct SqlConnection.
string s = connection.ConnectionString;
and check the datasource or server element of that row.
Edit: Given code example.
I think this feature should work (not tested anyway).
private bool CheckConnectionStringLocalOrRemote(string connectionString) {
//Local machine
IPHostEntry entry = Dns.GetHostByAddress("127.0.0.1");
IPAddress[] addresses = entry.AddressList;
String[] aliases = entry.Aliases;
string hostName = entry.HostName;
if(connectionString.Contains(hostName))
return true;
foreach (IPAddress address in addresses) {
if (connectionString.Contains(address.ToString())) {
return true;
}
}
foreach (string alias in aliases) {
if (connectionString.Contains(alias))
return true;
}
return false;
}
Ps: Make sure to add a using statement to the System.Net namespace.
a source to share
You can check the property SqlConnection.ConnectionString
to see if it has something like (local)
or .
in its part server
, but this is not very reliable because of %systemroot%\system32\drivers\etc\hosts' and various other SQL Aliases, whereby
foo-srv` it could very well be a local block.
a source to share