我正在尝试使用wpf应用程序中的 ManagementObject 类(.net 3.5)更改本地计算机的IP地址。
我在所有论坛中都使用了以下经过测试和验证的代码。 它在winform应用程序中成功更改了IP,但它在WPF桌面应用程序中不起作用。
WPF或其他任何方式都有限制吗?
internal static void SetNetworkAdaptorIP(string IpAddress, string subnetMask, string gateway)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] { this.txtGateway.Text };
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] { this.txtIP.Text };
objNewIP["SubnetMask"] = new string[] { this.txtSubnet.Text };
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!");
return;
}
catch (Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message);
}
}
}