c#中禁用和開啟網卡using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Collections;
namespace NetWorkControl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
NetWorkList();
}
/// <summary>
/// 網卡列表
/// </summary>
public void NetWorkList()
{
string manage = "SELECT * From Win32_NetworkAdapter";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
ManagementObjectCollection collection = searcher.Get();
List<string> netWorkList = new List<string>();
foreach (ManagementObject obj in collection)
{
netWorkList.Add(obj["Name"].ToString());
}
this.cmbNetWork.DataSource = netWorkList;
}
/// <summary>
/// 禁用網卡
/// </summary>5
/// <param name="netWorkName">網卡名</param>
/// <returns></returns>
public bool DisableNetWork(ManagementObject network)
{
try
{
network.InvokeMethod("Disable", null);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 啟用網卡
/// </summary>
/// <param name="netWorkName">網卡名</param>
/// <returns></returns>
public bool EnableNetWork(ManagementObject network)
{
try
{
network.InvokeMethod("Enable", null );
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 網卡狀態
/// </summary>
/// <param name="netWorkName">網卡名</param>
/// <returns></returns>
public bool NetWorkState(string netWorkName)
{
string netState = "SELECT * From Win32_NetworkAdapter";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject manage in collection)
{
if (manage["Name"].ToString() == netWorkName )
{
return true;
}
}
return false;
}
/// <summary>
/// 得到指定網卡
/// </summary>
/// <param name="networkname">網卡名字</param>
/// <returns></returns>
public ManagementObject NetWork(string networkname)
{
string netState = "SELECT * From Win32_NetworkAdapter";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject manage in collection)
{
if (manage["Name"].ToString() == networkname)
{
return manage;
}
}
return null;
}
private void btnStart_Click(object sender, EventArgs e)
{
if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
{
if (!EnableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
{
MessageBox.Show("開啟網卡失敗!");
}
else
{
MessageBox.Show("開啟網卡成功!");
}
}
else
{
MessageBox.Show("網卡己開啟!");
}
NetWorkList();
}
private void btnStop_Click(object sender, EventArgs e)
{
if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
{
if (!DisableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
{
MessageBox.Show("禁用網卡失敗!");
}
else
{
MessageBox.Show("禁用網卡成功!");
}
}
else
{
MessageBox.Show("網卡己禁用!");
}
NetWorkList();
}
}
}