如何更改适配器的IP地址?

时间:2014-11-19 07:39:15

标签: c# windows-7 network-programming

我想在适配器中设置IP地址。我得到了以下代码的几个参考。但执行此操作后,当我检查适配器ip地址时,它没有改变。它始终显示我的旧IP地址。没有给出任何错误/异常。 如何更改适配器的IP地址?

参考Dynamic-ip-change-in-c#

/// <summary>
        /// Set's a new IP Address and it's 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;
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

我知道这是一个迟到的答案,但我遇到了同样的问题并通过以管理员身份运行程序来解决它。我使用相同的技术(WMI),但使用不同的代码,我发布了here。希望有所帮助...