我想通过c#以编程方式在Windows 7中配置所有活动的网络适配器。
我尝试过以下代码:
string newIPAddress = "100.200.100.11";
string newSubnetMask = "255.255.255.1";
string[] newGateway = { "100.200.100.1" };
ManagementObjectSearcher m = new ManagementObjectSearcher();
m.Query = new ObjectQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True");
foreach (ManagementObject mo in m.Get())
{
try
{
ManagementBaseObject setIP;
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { newIPAddress };
newIP["SubnetMask"] = new string[] { newSubnetMask };
setIP = mo.InvokeMethod("EnableStatic", newIP, null);
mo.InvokeMethod("SetGateways", new object[] { newGateway, new string[] { "1" } });
mo.InvokeMethod("SetDNSServerSearchOrder", new object[] { new string[] { "100.100.100.100" } });
}
catch (Exception)
{
throw;
}
}
但它只更新默认网关并且不做任何其他更改。
我也使用过netsh命令:
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
Console.WriteLine(adapter.Name);
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"" + adapter.Name + "\" static 192.168.0.10 255.255.255.0 192.168.0.1 ");
psi.UseShellExecute = false;
p.StartInfo = psi;
p.Start();
}
但它适用于第一个适配器,之后它会产生错误:
“无法配置DHCP服务。接口可能已断开连接。”
如何在c#中配置所有适配器?
答案 0 :(得分:0)
我知道这篇文章已经过时但我相信你遇到了这个问题,因为你试图将多个适配器的IP设置为 Exact 相同的IP。