如果用户使用 Dsl 调制解调器连接,我使用此类检查 Internet 连接,下面的代码无法感知 Internet 连接
NetworkInterface.GetIsNetworkAvailable()
但是这个类可以解决这个问题,
class InternetConnectionChecker
{
private bool _connectingFlag = false;
private Thread _th;
#region Ping Google To Test Connect Or Disconnect
private string Ping()
{
try
{
const string remoteMachineNameOrIP = "173.194.78.104";
var ping = new Ping();
var reply = ping.Send(remoteMachineNameOrIP, 5);
var sb = new StringBuilder();
sb.Append(reply.Status.ToString());
return sb.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
#region Connecting Cheker Thread
private void ConCheck()
{
var status = Ping();
_connectingFlag = status == "Success" || status == "TimedOut";
}
public bool ConnectingCheker()
{
_th = new Thread(ConCheck);
_th.Start();
return _connectingFlag;
}
#endregion
}
供使用 //不要忘记创建全局实例 InternetConnectionChecker
InternetConnectionChecker _connectionChecker = new InternetConnectionChecker();
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
btn1.Content = _connectionChecker.ConnectingCheker();
}