c# - 使用 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"
) 我得到:
IP 地址无效
有关错误代码的完整列表,请参见此处
或者是否有另一种方法可以以编程方式更改 IP 地址(我需要根据其枚举名称进行更改,该名称将始终相同 - 恰好该名称与这台机器上的索引 15 匹配。)
编辑:如果你想试试,这里有一个 WMI 代码生成。
编辑 2:我也尝试过这个解决方案,但我会得到相同的2147786788
.
解决方案
推荐阅读
- css - 将输入类型日期更改为图标
- java - Android Keystore - 无效密钥异常 - 首选提供者不支持密钥(仅在模拟器上)
- multithreading - 如何使用 RxJava 让多个线程按顺序运行
- postgresql - statdard包中的非标准导入github.com/lib/pq
- android - 在改造中发布 JsonArray 时,会在 json 中自动添加一些 okhttp 内容
- spring - Spring:您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在附近使用的正确语法
- ios - 以编程方式兼容 iPhone X
- visual-studio-code - 如何在 vscode 中重复最后的 vim 动作?
- c# - 为什么这些具有相同哈希码的Action有不同的调用列表?
- soapui - 使用带有 Java 的 maven 插件重新运行失败的 SoapUI 测试