这篇文章整理了网上的资料,使用C#通过WMI修改IP、DNS等设置,希望能帮助到大家。
在项目引用中添加System.Management,然后在代码开头加上
using System.Management;
主程序段如下:
///
/// 设置所有适配器的属性
/// 如设置失败不会产生错误,请在设置后获取其当前值以检查是否成功
///
///IP地址
///子网掩码
///网关地址
///DNS服务器地址,如[0]为"back"即恢复为自动获取
public static 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);
}
else if (dns[0] == "back")
{
mo.InvokeMethod("SetDNSServerSearchOrder", null);
}
}
}
// TODO:代码里只有dns可以还原,其他的是使用重新开启DHCP的方法重置的,以后加入
额,大部分人已经知道怎么使用了,不过不知道,那再来一段实例吧:
///
/// 设置所有适配器的DNS服务器
/// 如设置失败不会产生错误,请在设置后获取当前DNS以检查是否成功
///
///首选DNS服务器地址,如为null则设置为自动获取
///备用DNS服务器地址,如为null且d1不为为null则备用为空
static void SetDNS(string d1, string d2)
{
if (d1 != null)
{
if (d2 != null)
{
SetNetwork(null, null, null, new string[] { d1, d2 });
}
else
{
SetNetwork(null, null, null, new string[] { d1 });
}
}
else
{
SetNetwork(null, null, null, new string[] { "back" });
}
}
写到这里应该明白了吧。。。不明白直接评论此文章问我~
请遵循Ms-PL许可证(自由使用,声明出处)
END OF RECORD返回顶部 ↑