终于完工了!奋战一个星期的晚上的成果。。。以后可能会继续完善吧。话不多说,直接上代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.NetworkInformation; using System.Management;
namespace TSLib.Net { /// <summary> /// TSLib 定义的网络适配器类 /// </summary> public class TSAdapter { private string name; private string description; private string serviceName; private OperationalStatus status; private NetworkInterfaceType type; private string[] dns; private Int32? interFace; private string gateway; private string ip; private string mask; /// <summary> /// 适配器的名称 /// </summary> public string Name { get { return name; } } /// <summary> /// 适配器的描述 /// </summary> public string Description { get { return description; } } /// <summary> /// 适配器的服务名 /// </summary> public string ServiceName { get { return serviceName; } } /// <summary> /// 适配器的状态 /// </summary> public OperationalStatus Status { get { return status; } } /// <summary> /// 适配器的类型 /// </summary> public NetworkInterfaceType Type { get { return type; } } /// <summary> /// 适配器的 DNS 服务器 /// <para> 可以设置 1~2 个 DNS,第二个为备用 DNS,赋为 null 切换回自动获取</para> /// </summary> public string[] DNS { get { return dns; } set { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); ManagementBaseObject i = null; ManagementBaseObject o = null; foreach (ManagementObject mo in moc) { if ((UInt32)mo["InterfaceIndex"] == Interface) { if (value == null) { UInt32 t; t = (UInt32)mo.InvokeMethod("SetDNSServerSearchOrder", null); if (t != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } else { i = mo.GetMethodParameters("SetDNSServerSearchOrder"); i["DNSServerSearchOrder"] = value; o = mo.InvokeMethod("SetDNSServerSearchOrder", i, null); if ((UInt32)o["returnValue"] != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } } } } } /// <summary> /// 适配器的接口 /// <para> 就是.NET 中的 Index</para> /// </summary> public Int32? Interface { get { return interFace; } } /// <summary> /// 适配器的网关 /// <para> 赋为 null 即将 IP、子网掩码、网关一同恢复为自动获取</para> /// </summary> public string Gateway { get { return gateway; } set { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); ManagementBaseObject i = null; ManagementBaseObject o = null; foreach (ManagementObject mo in moc) { if ((UInt32)mo["InterfaceIndex"] == Interface) { if (value == null) { i = mo.GetMethodParameters("EnableDHCP"); o = mo.InvokeMethod("EnableDHCP", i, null); if ((UInt32)o["returnValue"] != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } else { i = mo.GetMethodParameters("SetGateways"); i["DefaultIPGateway"] = new string[] { value }; o = mo.InvokeMethod("SetGateways", i, null); if ((UInt32)o["returnValue"] != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } } } } } /// <summary> /// 该适配器分配到的 IP 地址 /// <para> 如需更改,请使用 SetStatic 方法</para> /// </summary> public string IP { get { return ip; } } /// <summary> /// 适配器的子网掩码 /// <para> 如需更改,请使用 SetStatic 方法</para> /// </summary> public string Mask { get { return mask; } } void SetNetwork(string[] ip, string[] submask, string[] getway, string[] dns) { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; foreach (ManagementObject mo in moc) { //如果没有启用 IP 设置的网络设备则跳过 if (!(bool)mo["IPEnabled"]) continue; //设置 IP 地址和子网掩码 if (ip != null && submask != null) { inPar = mo.GetMethodParameters("EnableStatic"); inPar["IPAddress"] = ip; inPar["SubnetMask"] = submask; outPar = mo.InvokeMethod("EnableStatic", inPar, null); } //设置网关地址 if (getway != null) { inPar = mo.GetMethodParameters("SetGateways"); inPar["DefaultIPGateway"] = getway; outPar = mo.InvokeMethod("SetGateways", inPar, null); } //设置 DNS 地址 if (dns != null) { inPar = mo.GetMethodParameters("SetDNSServerSearchOrder"); inPar["DNSServerSearchOrder"] = dns; outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null); //outPar["returnValue"].ToString() } else if (dns[0] == "back") { mo.InvokeMethod("SetDNSServerSearchOrder", null); } } } /// <summary> /// 获取所有适配器的状态、属性 /// </summary> /// <returns> 每个适配器的泛型</returns> public static List<TSAdapter> GetAdapters() { List<TSAdapter> back = new List<TSAdapter>(); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter"); ManagementObjectCollection wmiadps = searcher.Get(); foreach (NetworkInterface adapter in adapters) { TSAdapter adp = new TSAdapter(); adp.name = adapter.Name; adp.description = adapter.Description; adp.status = adapter.OperationalStatus; adp.type = adapter.NetworkInterfaceType; IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); //IP if (uniCast.Count > 1) { if (uniCast[1].IPv4Mask != null) { adp.ip = uniCast[1].Address.ToString(); adp.mask = uniCast[1].IPv4Mask.ToString(); } } //网关 GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { adp.gateway = addresses[0].Address.ToString(); } //DNS IPAddressCollection dnsServers = adapterProperties.DnsAddresses; switch (dnsServers.Count) { case 1: adp.dns = new string[1]; adp.dns[0] = dnsServers[0].ToString(); break; case 2: adp.dns = new string[2]; adp.dns[0] = dnsServers[0].ToString(); adp.dns[1] = dnsServers[1].ToString(); break; } //Index if (p != null) { adp.interFace = p.Index; } //WMI 中的数据 foreach (ManagementObject mo in wmiadps) { if ((string)mo.GetPropertyValue("NetConnectionID") == adp.name) { //服务名称 adp.serviceName = (string)mo.GetPropertyValue("ServiceName"); } } back.Add(adp); } return back; } /// <summary> /// 获取所有适配器的报告 /// </summary> /// <returns> 带有换行符的所有适配器的报告</returns> public static string GetAdaptersReport() { List<TSAdapter> adps = GetAdapters(); string back = ""; foreach (TSAdapter adp in adps) { back += "==================================================\r\n"; back += "名称:" + adp.Name + "\r\n"; back += "描述:" + adp.Description + "\r\n"; back += "类型:" + adp.Type.ToString() + "\r\n"; back += "状态:" + adp.Status.ToString() + "\r\n"; back += "网关:" + adp.Gateway + "\r\n"; if (adp.DNS != null) { foreach (string d in adp.DNS) { back += "DNS:" + d + "\r\n"; } } back += "接口:" + adp.Interface + "\r\n"; back += "服务名:" + adp.ServiceName + "\r\n"; back += "IP:" + adp.IP + "\r\n"; back += "子网掩码:" + adp.Mask + "\r\n"; } return back; } /// <summary> /// 刷新适配器状态 /// </summary> public void Fresh() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter"); ManagementObjectCollection wmiadps = searcher.Get(); foreach (NetworkInterface adapter in adapters) { if (adapter.Name == name) { status = adapter.OperationalStatus; type = adapter.NetworkInterfaceType; IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); //IP if (uniCast.Count > 1) { if (uniCast[1].IPv4Mask != null) { ip = uniCast[1].Address.ToString(); mask = uniCast[1].IPv4Mask.ToString(); } } //网关 GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { gateway = addresses[0].Address.ToString(); } //DNS IPAddressCollection dnsServers = adapterProperties.DnsAddresses; switch (dnsServers.Count) { case 1: dns = new string[1]; dns[0] = dnsServers[0].ToString(); break; case 2: dns = new string[2]; dns[0] = dnsServers[0].ToString(); dns[1] = dnsServers[1].ToString(); break; } //Index if (p != null) { interFace = p.Index; } //WMI 中的数据 foreach (ManagementObject mo in wmiadps) { if ((string)mo.GetPropertyValue("NetConnectionID") == name) { //服务名称 serviceName = (string)mo.GetPropertyValue("ServiceName"); } } break; } } } /// <summary> /// 设置静态 IP 以及子网掩码 /// </summary> /// <param name="ip">IP 地址,如为 null 即设置 IP 与子网掩码为自动获取</param> /// <param name="mask"> 子网掩码,如为 null 即设置 IP 与子网掩码为自动获取</param> public void SetStatic(string ip,string mask) { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); ManagementBaseObject i = null; ManagementBaseObject o = null; foreach (ManagementObject mo in moc) { if ((UInt32)mo["InterfaceIndex"] == Interface) { if ((ip == null)||(mask == null)) { i = mo.GetMethodParameters("EnableDHCP"); o = mo.InvokeMethod("EnableDHCP", i, null); if ((UInt32)o["returnValue"] != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } else { i = mo.GetMethodParameters("EnableStatic"); i["IPAddress"] = new string[] { ip }; i["SubnetMask"] = new string[] { mask }; o = mo.InvokeMethod("EnableStatic", i, null); if ((UInt32)o["returnValue"] != 0) throw new TSAdapterSetException((UInt32)o["returnValue"]); break; } } } } /// <summary> /// 重写的基类 ToString 方法 /// </summary> /// <returns> 适配器的名称</returns> public override string ToString() { return this.name; } } //=================================================================================================== /// <summary> /// TSAdapter 设置异常类 /// </summary> public class TSAdapterSetException : Exception { private UInt32 code; /// <summary> /// 错误码 /// </summary> public UInt32 Code { get { return code; } } /// <summary> /// 错误描述 /// </summary> new public string Source { get; protected set; } /// <summary> /// 生成一个 TSAdapter 设置异常 /// </summary> /// <param name="c">WMI 返回的错误码</param> public TSAdapterSetException(UInt32 c) : base("设置时发生错误!错误码:" + c.ToString()) { code = c; switch (code) { case 1: Source = "设置已完成,但是需要重启。(环境特殊?)"; break; case 65: Source = "未知错误。"; break; case 66: Source = "无效子网掩码。"; break; case 70: Source = "无效 IP 地址。"; break; case 71: Source = "无效网关地址。"; break; case 91: Source = "拒绝访问。(需要管理员权限?)"; break; default: Source = "尚未翻译,请进入 http://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx 查询错误码"; break; } } } }
怎么使用呢?So easy!下面演示将 WLAN 2 适配器的 DNS 设置为谷歌的:
List<TSAdapter> Adps = TSAdapter.GetAdapters(); foreach (TSAdapter adp in Adps) { if (adp.Name == "WLAN 2") { try { adp.DNS = new string[] { "8.8.8.8" }; textBox1.Text = "OK"; } catch (TSAdapterSetException ee) { MessageBox.Show("设置时发生错误:" + ee.Source, "TSLib"); } break; } }
当然所有功能不能一一演示,用对象浏览器来看吧,全都加好 summary 的~
此类已收录在 TSLib.Net.TSAdapter,请遵循 Ms-PL 许可证(自由使用,声明出处)
更新喽~点击上面的链接进入查看最新版代码。
Comments | 2 条评论