使用ManagementObjects更改IP地址:IP地址不正确/锁定问题?

时间:2018-10-16 10:15:21

标签: c# .net windows windows-10 wmi

因此,我尝试使用ManagementObjects类以编程方式更改主机系统上的IP地址,并尝试使用 microsoft生成的代码进行如下更改:

public static void SetIPAddress()
        {
            try
            {
                ManagementObject classInstance =
                    new ManagementObject("root\\cimv2",
                    "Win32_NetworkAdapterConfiguration.Index='15'",
                    null);

                // Obtain in-parameters for the method
                ManagementBaseObject inParams =
                    classInstance.GetMethodParameters("EnableStatic");
                // I tried both of these, but neither seem to work
                //inParams["IPAddress"] = new string [] { "10", "13", "42", "1" };
                //inParams["SubnetMask"] = new string[] { "255", "255", "255", "0" };
                inParams["IPAddress"] = new string[] { "10.13.42.1" };
                inParams["SubnetMask"] = new string[] { "255.255.255.0" };


                // Execute the method and obtain the return values.
                ManagementBaseObject outParams =
                    classInstance.InvokeMethod("EnableStatic", inParams, null);

                // List outParams
                Console.WriteLine("Out parameters:");
                Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occurred while trying to execute the WMI method: " + err.Message);
            }
        }

我得到两个不同的错误代码(取决于IPAddres /子网掩码设置)。

使用格式:

        inParams["IPAddress"] = new string[] { "10.13.42.1" };
        inParams["SubnetMask"] = new string[] { "255.255.255.0" };

我得到Error Code 2147786788

Write lock not enabled. For more information, see INetCfgLock::AcquireWriteLock.

我使用从此处提供的确切锁定方法进行锁定:How to guarantee exclusive access when modifying network adapter properties

使用第二种格式("10", "13", "42", "1"),我得到:

Error code 70

Invalid IP Address

有关错误代码的完整列表,请参见Here

或者还有另一种方法可以通过编程方式更改IP地址(我需要根据其枚举名称进行更改,该名称将始终相同-恰好该名称与本机上的索引15匹配。)< / p>

编辑:如果您想尝试,可以使用a WMI code generate here

编辑2:我也尝试过this解决方案,但我会得到相同的2147786788

0 个答案:

没有答案