Search code examples
c#powershell-3.0

how to ADD IP address in Windows 10 using C#


I want to add multiple IP addresses in my Ethernet port. I tried below both way

  1. using Management 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. Using PowerShellSCript in C#

    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();
        }
    

Both are not working, my code working properly it's not going inside catch, but not able to add IP, even I can add IP using running power script file from Windows PowerShell, but the same script is not working inside C#,

all I am trying to add a number of IP address in Single Ethernet card

Note: yes I have Admin rights, I already perform this manually and using PowerShell tool power script. one more thing, every time i have to right-click window PowerShell and run as administrator to run my scrip


Solution

  • Problem Solved, Run Exe As a administratoror, Run Visual studio as a Administrator .

    I go further and added multiple IP addresses, and Subnet makst in Single Ethernet card

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