C#通过 WMI 修改 IP、DNS 等设置

发布于 2014-03-07  1017 次阅读


以下功能已全面整合在 TSAdapter 类 – 通过 C#获取/设置名称、状态、IP、DNS、网关、接口等信息

这篇文章整理了网上的资料,使用 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 许可证(自由使用,声明出处)

寻找属于自己的1%