我想通过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#中配置所有适配器?
我知道这篇文章是旧的,但我相信你有这个问题,因为你正试图将多个适配器的IP设置为确切的相同的IP。