Kiểm tra tình trạng kết nối internet của máy tính trong C#, thường dùng để kiểm tra tình trạng Internet trước khi thực hiện kết nối tới SQL Server

Tạo class clsInternet.cs với đoạn code sau
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
[Flags]
enum ConnectionInternetState : int
{
INTERNET_CONNECTION_MODEM = 0x1, INTERNET_CONNECTION_LAN = 0x2, INTERNET_CONNECTION_PROXY = 0x4, INTERNET_RAS_INSTALLED = 0x10, INTERNET_CONNECTION_OFFLINE = 0x20, INTERNET_CONNECTION_CONFIGURED = 0x40
}
public class clsInternet
{
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(ref ConnectionInternetState lpdwFlags, int dwReserved);
public clsInternet()
{
}
public static bool IsConnectedToInternet()
{
ConnectionInternetState Description = 0;
bool conn = InternetGetConnectedState(ref Description, 0);
return conn;
}
}
Sử dụng: Trong sự kiện Load của form (giả sử là Form1), dùng đoạn code sau, nếu hiện thông báo True thì máy tính đang kết nối Internet
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(clsInternet.IsConnectedToInternet().ToString());
}
