2015-04-04 74 views

回答

2

我從Connection.DataSource獲取服務器的IP地址(DNS名稱)。然後我檢查一下,是否有此名稱的列表:

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 
} 

方法:

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(); 
} 

數據源可以是:

  • serverName1
  • serverName1,1433 \ SQLEXPRESS
  • 192.168.0.1
  • tcp:192.168.0.1,1433 \ SQLEXPRESS
  • ...