Click here to Skip to main content
15,920,708 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi everyone

I'm a c# newby who want to learn more about programming. So I started with a simple tool, wich can set the address of a choosen network adapter to static or dynamic (like the Windows TCP/IP Properties. Setting a static IP address to the network adapter works pretty good. But when I disconnet the Computer form the network and then set the network adapter's IP to dynamic (Obtain an IP address automatically"), it won't set the Windows IP Propertie to dynamic. I understand that I only get an IP address automatically, when I'm connected to a network (where a router or a DHCP server is enabled). But when I disconnect the computer form the network, an I set the IP Properties to dynamic with the the Windows TCP/IP Properties, it works well. What is worng in my code?

Thanks for your help!

Below the code I'm using:

public void setDHCPMode()
   {
       ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
       ManagementObjectCollection moc = mc.GetInstances();

       foreach (ManagementObject mo in moc)
       {
           if (!(bool)mo["ipEnabled"])
               continue;

           try
           {
               string desc = (string)(mo["Description"]);

               if (desc == NICcomboBox.Text)
               {
                   ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
                   newDNS["DNSServerSearchOrder"] = null;
                   ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
                   ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
               }

               toolStripStatusLabel1.Text = "DHCP set";
           }
           catch (Exception ex)
           {
               MessageBox.Show("Unable to set DHCP : " + ex.Message);
           }
       }
   }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900