首页 > 解决方案 > 使用 ManagementObjects 更改 IP 地址:不正确的 IP 地址/锁定问题?

问题描述

因此,我尝试使用 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" };

我得到错误代码 2147786788

未启用写锁定。有关详细信息,请参阅 INetCfgLock::AcquireWriteLock。

我有一个使用这里提供的确切锁定方法的锁。

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

错误代码 70

IP 地址无效

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

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

编辑:如果你想试试,这里有一个 WMI 代码生成

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

标签: c#.netwindowswindows-10wmi

解决方案


推荐阅读