可靠的互联网连接对于无缝应用程序体验至关重要。对于使用 .NET 的开发人员来说,找到一种有效的方法来检查互联网可用性至关重要。让我们探索应对这一挑战的最佳方法。
在各种可用的方法中,.NET 中最有效、最稳健的方法是利用 HttpWebRequest班级。此技术允许自定义超时设置,并克服了可能阻碍特定区域的连接测试的地理限制。
要实现此方法,可以使用以下代码片段:
public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null) { try { url ??= CultureInfo.InstalledUICulture switch { { Name: var n } when n.StartsWith("fa") => // Iran "http://www.aparat.com", { Name: var n } when n.StartsWith("zh") => // China "http://www.baidu.com", _ => "http://www.gstatic.com/generate_204", }; var request = (HttpWebRequest)WebRequest.Create(url); request.KeepAlive = false; request.Timeout = timeoutMs; using (var response = (HttpWebResponse)request.GetResponse()) return true; } catch { return false; } }
这种方法提供了几个关键优点:
以上是如何可靠地检查.NET中的Internet连接?的详细内容。更多信息请关注PHP中文网其他相关文章!