I want know when my app run locally on SQL Server. It is necessary for backup and restore.
I get the IP address(DNS name) of the server from the Connection.DataSource. And then I check, whether there is this name in the list:
localNames = new List<string>()
{
".", "localhost", "(local)", "127.0.0.1", Environment.MachineName.ToLower(),
};
localNames.AddRange(GetIP().Select(a=>a.ToString()));
if (localNames.Contains(GetServer(connection.DataSource).ToLower()))
{
//do something
}
methods:
IEnumerable<IPAddress> GetIP()
{
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork))
{
yield return ip;
}
}
string GetServer(string dataSource)
{
return dataSource.Split('\\').First().Split(',').First().Split(':').Last();
}
DataSource can be: