Home > Backend Development > C++ > How Can I Efficiently Check for Internet Connectivity in .NET Applications?

How Can I Efficiently Check for Internet Connectivity in .NET Applications?

Patricia Arquette
Release: 2025-01-25 19:46:09
Original
184 people have browsed it

How Can I Efficiently Check for Internet Connectivity in .NET Applications?

High-Performance Internet Connectivity Testing in .NET Applications

The Challenge:

Determining internet connectivity quickly and reliably within .NET applications, especially in regions with potential website restrictions (e.g., Iran, China), presents a significant challenge.

The Solution:

This optimized code snippet provides a fast and efficient method for verifying internet access:

<code class="language-csharp">public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
    try
    {
        // Selects a suitable URL based on the system's UI culture.
        url = url ?? CultureInfo.InstalledUICulture.Name switch
        {
            var n when n.StartsWith("fa") => "http://www.aparat.com", // Iran
            var n when n.StartsWith("zh") => "http://www.baidu.com", // China
            _ => "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; // Success: Internet connection established.
    }
    catch (Exception)
    {
        return false; // Failure: No internet connection.
    }
}</code>
Copy after login

This approach ensures robust internet connectivity checks in your .NET applications, even under geographically diverse network conditions. The use of different default URLs helps to overcome regional restrictions.

The above is the detailed content of How Can I Efficiently Check for Internet Connectivity in .NET Applications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template