How do I change the IP address of the adapter?

I want to set the IP address in the adapter. I got some links for the code below. but after doing this, when I check the adapter ip address, it doesn't change. It always shows me the old ip address. Don't specify any errors / exceptions. How do I change the IP address of the adapter?

Refere Dynamic-ip-change-in-C #

/// <summary>
        /// Set a new IP Address and it Submask of the local machine
        /// </summary>
        /// <param name="ipAaddress">The IP Address</param>
        /// <param name="subnetMask">The Submask IP Address</param>
        /// <remarks>Requires a reference to the System.Management namespace</remarks>
        public void SetIP(string ipAaddress, string subnetMask)
        {
            ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if ((bool)managementObject["IPEnabled"])
                {
                    try
                    {       
                        string[] addresses = (string[])managementObject["IPAddress"];
                        //Console.WriteLine(addresses[0]);
                        if (addresses[0] == "xxx.xx.xxx.xx")                                 //xxx.xx.xxx.xx should be some valid ip
                        {
                            ManagementBaseObject managementBaseObjectNew = managementObject.GetMethodParameters("EnableStatic");
                            managementBaseObjectNew["IPAddress"] = new string[] { ipAaddress };
                            managementBaseObjectNew["SubnetMask"] = new string[] { subnetMask };
                            ManagementBaseObject managementBaseObjectSet = managementObject.InvokeMethod("EnableStatic", managementBaseObjectNew, null);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
        }

      

+3


source to share


1 answer


I know this is a late answer, but I ran into the same problem and solved it by running the program as administrator. I used the same technique (WMI) but with different code that I posted here . Hope it helps ...



0


source







All Articles