I was recently in the process of rolling my own library to be able to drop into an application to make it "network aware" i.e. the application can periodically check to make sure it still has a network connection...I've seen plenty of apps in the past that completely lock up if there is even the slightest network hiccup; invariably you have to zap it with task manager with the caveat of losing whatever you were working on.
The library itself was to be easy enough...just execute a simple ping request on a threading timer at a specified interval, if the request fails raise an event letting calling code know that there is a problem with the network connection. Sounds easy enough, but about an hour into it I thought "there has got to be an easier way outside of doing raw Win32 or WMI hookups."
Lo and behold there is: Enter the System.Net.NetworkInformation namespace, which is new to .Net 2.0. In it you'll find a variety of classes dealing with numerous aspects of of how your machine is connected to the network, details about the network interface itself, and statistics gathering for network traffic.
The core class for checking on network availability is the NetworkChange class, which contains 2 core events: the NetworkAddressChanged event and the NetworkAvailabilityChanged event. By hooking up to these events, you can get (almost) real-time notifications of network changes, and thus provide your users with a transparent experience should network connectivity be interrupted (i.e. saving their work, switching to a local data repository, etc) You can also proactively check network availability by polling the NetworkInterface.GetIsNetworkAvailable method, which returns true if any NIC on the machine has a connection deemed "up and running" by the .Net framework. And of course the trusty Ping class resides in this namespace as well, which was one of the most requested networking functions missing from the 1.x releases of .Net.
This namespace is a welcome addition to the framework, especially as the number of applications that need to be network aware are in the majority now.
Posted
Jan 23 2007, 07:13 PM
by
Jayson Knight