1

我想通过 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# 中配置所有适配器?

4

1 回答 1

0

我知道这篇文章很旧,但我相信您遇到了这个问题,因为您正在尝试将多个适配器的 IP 设置为完全相同的IP。

于 2014-11-26T14:46:42.357 回答