一般每个人至少有两种使用计算机的环境:单位工作场所和家。如果这两个场景使用计算机都是使用自动获取IP地址的话,那么可以略过这篇文章了。笔者使用的场景是:家里是自动获取IP地址的,而单位里是使用的静态IP地址。在这种情况下,把笔记本带到家中和单位,总要手工设置IP,才能正常使用网络。
看了上面的内容,如果还想要继续往下看的,那么就是跟我的情况相似了。那么就Follow Me!
1.界面如下
2.需要作一下dll引用
3.名称空间引用
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.IO;
using System.Net;
4.修改按钮代码如下:
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
if (mo["Description"].ToString() == comboBox1.SelectedItem.ToString().Trim())
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
// 将要修改的目标 IP 地址
// string selectNewIP;
string IPStr = "";
string[] IPPart = ipAdd.Text.Split('.');
for (int i = 0; i <= 3; i++)
{
//删除尾部首部的空格
IPStr += (IPPart[i].Trim() + ".");
}
IPStr = IPStr.Substring(0, IPStr.Length - 1);
newIP["IPAddress"] = new string[] { IPStr };
//设置子网掩码
string subStr = "";
string[] subPart = subMask.Text.Split('.');
for (int i = 0; i <= 3; i++)
{
//删除尾部首部的空格
subStr += (subPart[i].Trim() + ".");
}
subStr = subStr.Substring(0, subStr.Length - 1);
newIP["SubnetMask"] = new string[] { subStr };
//设置网关地址
string gatStr = "";
string[] gatPart = gateWay.Text.Split('.');
for (int i = 0; i <= 3; i++)
{
gatStr += (gatPart[i].Trim() + ".");
}
gatStr = gatStr.Substring(0, gatStr.Length - 1);
newGateway["DefaultIPGateway"] = new string[] { gatStr };
// 将要修改的目标 DNS 首选地址
string dnsStr1 = "";
string[] dnsPart1 = DNS1.Text.Split('.');
for (int i = 0; i <= 3; i++)
{
dnsStr1 += (dnsPart1[i].Trim() + ".");
}
dnsStr1 = dnsStr1.Substring(0, dnsStr1.Length - 1);
// 将要修改的目标 DNS 备用地址
string dnsStr2 = "";
if (DNS2.Text.Trim()!="")
{
string[] dnsPart2 = DNS2.Text.Split('.');
for (int i = 0; i <= 3; i++)
{
dnsStr2 += (dnsPart2[i].Trim() + ".");
}
dnsStr2 = dnsStr2.Substring(0, dnsStr2.Length - 1);
newDNS["DNSServerSearchOrder"] = new string[] { dnsStr1, dnsStr2 };
}
else
newDNS["DNSServerSearchOrder"] = new string[] { dnsStr1 };
// 修改网络设置
try
{
ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGateway, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
MessageBox.Show("设置成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
}
}
5.自动获取代码如下
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
if (mo["Description"].ToString() == comboBox1.SelectedItem.ToString().Trim())
{
//重置DNS为空
mo.InvokeMethod("SetDNSServerSearchOrder", null);
//开启DHCP
mo.InvokeMethod("EnableDHCP", null);
MessageBox.Show("自动获取IP成功!");
break;
}
}
}
6.保存配置文件代码
try
{
string path = Application.StartupPath + "\\config.ini";
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(ipAdd.Text);
sw.WriteLine(subMask.Text);
sw.WriteLine(gateWay.Text);
sw.WriteLine(DNS1.Text);
sw.WriteLine(DNS2.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("写入配置文件错误!" + ex.Message);
}
7. 退出代码
Application.Exit();
8.窗体Load事件代码
string carName = "";
ManagementObjectSearcher search = new ManagementObjectSearcher("SELECT * FROM Win32_NetWorkAdapterConfiguration");
foreach (ManagementObject sear in search.Get())
{
if (sear["IPAddress"] != null)
{
carName = sear["Description"].ToString().Trim();
comboBox1.Items.Add(carName);
}
}
comboBox1.SelectedIndex = 0;
string path=Application.StartupPath+"\\config.ini";
if(File.Exists(path))
{
using (StreamReader sr = File.OpenText(path))
{
ipAdd.Text = sr.ReadLine();
subMask.Text = sr.ReadLine();
gateWay.Text = sr.ReadLine();
DNS1.Text = sr.ReadLine();
DNS2.Text = sr.ReadLine();
}
}
else
{
ShowInfo();
}
9.自定义方法 ShowInfo()
public void ShowInfo()
{
ManagementClass myMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection myMOCollection = myMClass.GetInstances();
foreach (ManagementObject MObject in myMOCollection)
{
if (!(bool)MObject["IPEnabled"])
continue;
string[] strIP = (string[])MObject["IPAddress"]; //获取IP地址
string[] strSubnet = (string[])MObject["IPSubnet"]; //获取子网掩码
string[] strGateway = (string[])MObject["DefaultIPGateway"];//获取默认网关
string[] strDns = (string[])MObject["DNSServerSearchOrder"];//获取DNS服务器
ipAdd.Text = "";
//显示IP地址
foreach (string ip in strIP)
{
IPAddress ipaddress = IPAddress.Parse(ip);
if (ipaddress.AddressFamily.ToString() != "InterNetwork")
continue;
if (ipAdd.Text.Trim() != "")
{
ipAdd.Text += "," + ip;
}
else
{
ipAdd.Text = ip;
}
}
subMask.Text = "";
//显示子网掩码
foreach (string subnet in strSubnet)
{
if (subnet.IndexOf('.') <= 0)
continue;
if (subMask.Text.Trim() != "")
{
subMask.Text += "," + subnet;
}
else
{
subMask.Text = subnet;
}
}
gateWay.Text = "";
//显示默认网关
foreach (string gateway in strGateway)
{
IPAddress ipaddress = IPAddress.Parse(gateway);
if (ipaddress.AddressFamily.ToString() != "InterNetwork")
continue;
if (gateWay.Text.Trim() != "")
{
gateWay.Text += "," + gateway;
}
else
{
gateWay.Text = gateway;
}
}
try
{
//显示DNS服务器
for (int i = 0; i < strDns.Length; i++)
{
if (i == 0)
DNS1.Text = strDns[i];
else
DNS2.Text = strDns[i];
}
}
catch { }
}
}
喜欢我的文章和教程请关注!