如何使用 C# 在 Windows 10 中添加 IP 地址

how to ADD IP address in Windows 10 using C#

我想在我的以太网端口中添加多个 IP 地址。 我尝试了以下两种方式

  1. 使用管理Class

    public void setIP()
        {
            string myDesc = "Realtek USB GbE Family Controller";
            string gateway = "10.210.255.1";
            string subnetMask = "255.255.255.0";
            string address = "10.210.255.102";
    
            var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var networkCollection = adapterConfig.GetInstances();
    
            foreach (ManagementObject adapter in networkCollection)
            {
                string description = adapter["Description"] as string;
                if (string.Compare(description,
                    myDesc, StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    try
                    {
                        // Set DefaultGateway
                        var newGateway = adapter.GetMethodParameters("SetGateways");
                        newGateway["DefaultIPGateway"] = new string[] { gateway };
                        newGateway["GatewayCostMetric"] = new int[] { 1 };
    
                        // Set IPAddress and Subnet Mask
                        var newAddress = adapter.GetMethodParameters("EnableStatic");
                        newAddress["IPAddress"] = new string[] { address };
                        newAddress["SubnetMask"] = new string[] { subnetMask };
    
                        adapter.InvokeMethod("EnableStatic", newAddress, null);
                        adapter.InvokeMethod("SetGateways", newGateway, null);
    
                        Console.WriteLine("Updated to static IP address!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to Set IP : " + ex.Message);
                    }
                }
            }
        }
    
  2. 在 C# 中使用 PowerShellSCript

    private string RunScript()
        {
    
                  string scriptText = "$iplist = \"10.210.255.102\"" + "," + " \"10.210.255.103\"" + "\nforeach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}";
    
            // create Powershell runspace
    
            Runspace runspace = RunspaceFactory.CreateRunspace();
    
            // open it
    
            runspace.Open();
    
            // create a pipeline and feed it the script text
    
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
    
            // add an extra command to transform the script
            // output objects into nicely formatted strings
    
            // remove this line to get the actual objects
            // that the script returns. For example, the script
    
            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.
    
            pipeline.Commands.Add("Out-String");
    
            // execute the script
    
            var results = pipeline.Invoke();
    
            // close the runspace
    
            runspace.Close();
    
            // convert the script result into a single string
    
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
    
            return stringBuilder.ToString();
        }
    

两者都不工作,我的代码工作正常,它没有进入 catch, 但无法添加IP, 即使我可以使用 Windows PowerShell 中的 运行ning power 脚本文件添加 IP,但相同的脚本在 C# 中不起作用,

我正在尝试在单个以太网卡中添加多个 IP 地址

注意:是的,我拥有管理员权限,我已经手动执行此操作并使用 PowerShell 工具电源脚本。 还有一件事, 每次我必须以管理员身份右键单击 window PowerShell 和 运行 到 运行 我的 scrip

对于 Powershell 解决方案,让脚本在 C# 中运行真的很痛苦。通常我更喜欢使用Powershell class,你可以试试这个方法:

使用脚本:

var Ps = PowerShell.Create();
//you can create the variable like this:
Ps.AddCommand("Set-Variable").AddParameter("Name", "tsinfo").AddParameter("Value", result);
Ps.Invoke();
//Execute your script
Ps.Commands.Clear();
Ps.AddScript("foreach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}");
Ps.Invoke();

或使用命令:

var iplist = new List<string> { "10.210.255.102", "10.210.255.103"};
foreach(var ip in iplist){
    Ps.Commands.Clear();
    Ps.AddCommand("New-NetIPAddress").AddParameter("InterfaceAlias", "Ethernet").AddParameter("IPAddress", ip).AddParameter("PrefixLength", 24);
    Ps.Invoke();
}

希望对您有所帮助

问题已解决,运行 以管理员身份执行或,运行 Visual studio 以管理员身份执行。

我更进一步,在单个以太网卡中添加了多个 IP 地址和子网标记

var newAddress = adapter.GetMethodParameters("EnableStatic");
                        newAddress["IPAddress"] = new string[] { address, address1 };
                        newAddress["SubnetMask"] = new string[] { subnetMask,subnetMask };

                        var cal1 = adapter.InvokeMethod("EnableStatic", newAddress, null);