How to Monitor Network Connectivity in .NET
There is a common problem with smart client applications that they need to implement monitoring network connectivity. Common scenario - if the computer is connected - send data to the server, otherwise - serialize data to disk, then wait for network connectivity becomes available and when the network is available - send serialized data to the server in the background.
.NET 2.0 introduced System.Net.NetworkInformation with NetworkAvailabilityChanged event, so there is no need to reinvent network monitor behavior by hand any more :)
Use the right namespace :)
using System.Net.NetworkInformation;
Now it is possible to check connectivity on demand...
bool connected = NetworkInterface.GetIsNetworkAvailable();
Or subscribe to event in some place....
NetworkChange.NetworkAvailabilityChanged += OnAvaiabilityChanged;
Implement like so:
private void OnAvaiabilityChanged(object sender,
NetworkAvailabilityEventArgs args)
{
this.UpdateStatus(args.IsAvailable);
}
private void UpdateStatus(bool connected)
{
if (connected)
{
...
}
else
{
...
}
}
Enjoy :)
Friday, June 8, 2007 8:07 PM