C# 用C语言编程配置Win7网络适配器#

C# 用C语言编程配置Win7网络适配器#,c#,windows,networking,system.security,C#,Windows,Networking,System.security,我想通过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(

我想通过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。

在命令行中运行
ipconfig/all
,你会看到它确实显示断开连接的网络适配器,所以它不是真的抛出错误。谢谢回复。在运行netsh代码后启用的适配器中,唯一的更改是“自动获取IP地址”更改为“使用以下IP”,但没有IP地址。此外,我猜每次创建新进程都不是配置网络适配器的有效方法。我们可能会结束大量zoombie进程的运行。这并不能回答这个问题。若要评论或要求作者澄清,请在他们的帖子下方留下评论-你可以随时在自己的帖子上发表评论,一旦你有足够的评论,你就可以发表评论。我最近遇到了与恶魔猎人相同的问题,因为我无意中试图将所有适配器设置为完全相同的IP。我只是想帮忙!