How to detect Network connection in VB.Net? PDF Print E-mail
Written by J. Bijvoets   
Saturday, 09 January 2010 19:40

Detecting network connection in Visual Basic.net

One of the common situations you can stumble into is your assumption your computer is connected to the network, but your Visual Basic application has other thoughts about it, resulting in a crash of your application. You could write some error trapping code to repair the damage, but better is to anticipate the situation, and detect in the proper way if your computer is connected to the network before assuming so.

Here's the simple trick to do it: use My.Computer.Network.IsAvailable to check the existence of a working network connection.

Try the following code:

If My.Computer.Network.IsAvailable then
MsgBox("Network detected!")
Else
MsgBox("Network connection is not found!")
End If

As a matter of fact, Microsoft thought this code so useful, they wrote a Code Snippet for it. Look in the Code Snippets for the Connectivity and Networking subject, find the snippet Determine if the Network is Available, and you'll get:

Dim isAvailable = My.Computer.Network.IsAvailable

Don't hesitate to look after the other code snippets, by the way, they're quite useful now and then for solving your problems.

Try some other time to examine the My-object. It is very useful also.

Last Updated on Tuesday, 23 November 2010 20:54