Check internet connection in Silverlight

2019-02-26 00:53发布

问题:

I'm writing a Silverlight 4 application and would like to check when opening the installed out of browser application, whether there is a valid internet connection (to then download some data from my website). What is the best way to do this? I realise that I could put a try catch around a WebRequest but that seems a bit hacky to me.

EDIT: What I meant by valid internet connection is just connected to the internet

回答1:

You can just kill two birds with one stone with Application.CheckAndDownloadUpdateAsync. When you get a False on UpdateAvailable in handling Application.CheckAndDownloadUpdateCompleted, it's going to mean either one of two things - your site can't be reached or there is no update available. In either case, you'll know what you need to know.



回答2:

What exactly is a valid Internet connection? If you want to check for your ability to download data from your site, check to see if you can download from your site. There's nothing very hacky about putting a try/catch block around something that might fail for reasons beyond your program's control. It's exactly what I would do.

That the client is "connected to the Internet" does not necessarily mean that your site is available to serve the data that you want. That is the only valid thing to test.



回答3:

There is a class called NetworkInterface that will allow this.

 if (!NetworkInterface.GetIsNetworkAvailable())
 { 
      // no network connection
 }

Now this isn't guaranteed to always determine whether there is a internet connection of not, depending on proxy settings and other variables.

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx