日期:2014-05-17 浏览次数:20862 次
/// <summary> /// 设置IP 子网掩码、默认网关和DNS /// </summary> /// <param name="ip">IP</param> /// <param name="subnetmask">子网掩码</param> /// <param name="gateway">默认网关</param> /// <param name="dns">DNS</param> private bool SetNetworkAdapter(string ip, string subnetmask, string gateway, string dns, string mode) { bool success = true; ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (mo["Description"].ToString().Trim() == lbCards.SelectedValue.ToString().Trim()) { if (!(bool)mo["IPEnabled"]) { MessageBox.Show("已检测到网卡,但无法设置。请检查网卡优先性并确认是否已被禁用或已插网线。"); Process.Start("ncpa.cpl");//网络连接 break; } else { try { if (mode == "auto") { //重置DNS为空 mo.InvokeMethod("SetDNSServerSearchOrder", null); //开启DHCP mo.InvokeMethod("EnableDHCP", null); success = true; break; } else if (mode == "hand") { //设置ip地址和子网掩码 inPar = mo.GetMethodParameters("EnableStatic"); inPar["IPAddress"] = new string[] { ip };// 1.备用 2.IP inPar["SubnetMask"] = new string[] { subnetmask }; outPar = mo.InvokeMethod("EnableStatic", inPar, null); //设置网关地址 if (gateway.Equals(String.Empty)) { mo.InvokeMethod("SetGateways", null); } else { inPar = mo.GetMethodParameters("SetGateways"); inPar["DefaultIPGateway"] = new string[] { gateway }; // 1.网关;2.备用网关 outPar = mo.InvokeMethod("SetGateways", inPar, null); } //设置DNS if (dns.Equals(String.Empty)) { mo.InvokeMethod("SetDNSServerSearchOrder", null); } else { inPar = mo.GetMethodParameters("SetDNSServerSearchOrder"); inPar["DNSServerSearchOrder"] = new string[] { dns }; // 1.DNS 2.备用DNS outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null); } success = true;