If you need to check the state of your network connection in C#, I know of 2 ways (that I’m aware of) to do this:
1. Steal from VB
You can use the VB “My” functions by importing the Microsoft.VisualBasic assembly into your project.
In VB, you would normally use the following code:
My.Computer.Network.IsAvailable
In C#, you can use following code:
Microsoft.VisualBasic.Devices.Network network = new Microsoft.VisualBasic.Devices.Network();
Console.WriteLine(network.IsAvailable);
2. PInvoke
If you don’t want to bring a VB reference into your C# project (which shouldn’t really be a problem), you can always resort to PInvoking the native windows API’s.
Below is the code to code natively:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsConnectedToInternet().ToString());
}
[DllImport("wininet.dll", SetLastError = true)]
extern static bool InternetGetConnectedState(
out InternetGetConnectedStateFlags Description, int ReservedValue);
[Flags]
enum InternetGetConnectedStateFlags
{
INTERNET_CONNECTION_MODEM = 0x01,
INTERNET_CONNECTION_LAN = 0x02,
INTERNET_CONNECTION_PROXY = 0x04,
INTERNET_CONNECTION_RAS_INSTALLED = 0x10,
INTERNET_CONNECTION_OFFLINE = 0x20,
INTERNET_CONNECTION_CONFIGURED = 0x40
}
public static bool IsConnectedToInternet()
{
InternetGetConnectedStateFlags flags;
var ret = InternetGetConnectedState(out flags, 0);
Console.WriteLine(flags.ToString());
return ret;
}
}
(I also updated pinvoke.net with this info)
Notes:
1. The Pinvoke method will give you an more detail by giving you an out parameter showing which connections are available to you
2. These methods will only tell you if the network device is connected. It won’t tell you if you have can get out to the internet.