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