日期:2014-05-17  浏览次数:21328 次

WMI根据选定网卡修改IP
我用的是这样的
C# code

public bool ModIP(ip myIP)
        {
            bool isSuccess = false;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                {
                    myIP.Mac = mo["MacAddress"].ToString();
                    try
                    {
                        //设置IP地址和子网掩码
                        ManagementBaseObject newIPSubMask = mo.GetMethodParameters("EnableStatic");
                        newIPSubMask["IPAddress"] = new string[] { myIP.Ip };
                        newIPSubMask["SubnetMask"] = new string[] { myIP.Subnetmask };
                        ManagementBaseObject setIPSubMask = mo.InvokeMethod("EnableStatic", newIPSubMask, null);
                        //设置
                        //ManagementBaseObject newSubMask = mo.GetMethodParameters("EnableStatic");
                        //newSubMask["SubnetMask"] = new string[] { myIP.Subnetmask };
                        //ManagementBaseObject setSubMask = mo.InvokeMethod("EnableStatic", newSubMask, null);

                        //设置网关
                        ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
                        newGate["DefaultIPGateway"] = new string[] { myIP.Gateway };
                        ManagementBaseObject setGateway = mo.InvokeMethod("SetGateways", newGate, null);

                        //设置DNS
                        ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        newDNS["DNSServerSearchOrder"] = new string[] { myIP.Dns1, myIP.Dns2 };
                        ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                        isSuccess = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("原因:" + ex);
                        isSuccess = false;
                    }
                }
            }
            return isSuccess;
        }



但是这个的不好之处就是会把现在使用的所有网卡,像无线啊什么的IP地址都改了,想弄个下拉条选择网卡,根据选择的网卡来修改IP。
我弄了一个只能读取网卡的
C# code

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;




高手来解决一下吧

------解决方案--------------------
ding!!