怎样用C#代码知道是否已连接网络

时间:2023-03-08 17:08:56
怎样用C#代码知道是否已连接网络

有时,上传数据和下载数据都需要用到网络,但是不知道程序是否已连接到网络,下面是简单测试是否已连接网络的小功能

1、在winform窗体上添加一个按钮和多选框

怎样用C#代码知道是否已连接网络

2、点击检查网络,触发事件,如果是有网络,则勾上网络状态,失败则提示

怎样用C#代码知道是否已连接网络

3、事件的源码

private void button1_Click(object sender, EventArgs e)
        {
            System.Net.NetworkInformation.Ping ping;
            System.Net.NetworkInformation.PingReply res;
            ping = new Ping();
            try
            {
                res = ping.Send("www.baidu.com");   //相当于控制台ping www.baidu.com
                if (res.Status == IPStatus.Success)   //判断ping是否成功
                {
                    MessageBox.Show("已连接");
                    this.checkBox1.Checked = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("网络连接异常,请检查网络!");
                this.checkBox1.Checked = false;
            }
        }