日期:2014-05-18  浏览次数:20841 次

C#中,如何在“自动分配IP和DNS”与“固定IP和DNS”两种状态中动态切换?
在网络上找到一些动态设置IP和DNS的代码,都试验成功了。但把它切换为“动态分配IP和DNS”时,却不成功?不知道是否是代码错了,还是缺少一些代码?
C# code
static void SwitchToDHCP()
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                inPar = mo.GetMethodParameters("EnableDHCP");
                outPar = mo.InvokeMethod("EnableDHCP", inPar, null);
                break;
            }
        }


------解决方案--------------------
C# code

//自动获取IP
public void EnableDHCP()
         {
             foreach (ManagementObject mo in moc)
             {
                if (!(bool)mo["IPEnabled"]) continue;

                if (!(bool)mo["DHCPEnabled"])
                {
                    iObj = mo.GetMethodParameters("EnableDHCP");
                    oObj = mo.InvokeMethod("EnableDHCP", iObj, null);
                }
            }
        }