What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2064
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

27条回答
  •  攒了一身酷
    2020-11-22 08:29

    For my application we also test by download tiny file.

    string remoteUri = "https://www.microsoft.com/favicon.ico"
    
    WebClient myWebClient = new WebClient();
    
    try
    {
        byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);
        if(myDataBuffer.length > 0) // Or add more validate. eg. checksum
        {
            return true;
        }
    }
    catch
    {
        return false;
    }
    

    Also. Some ISP may use middle server to cache file. Add random unused parameter eg. https://www.microsoft.com/favicon.ico?req=random_number Can prevent caching.

提交回复
热议问题