Click here to Skip to main content
15,888,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add multiple IP addresses in my Ethernet port.
I tried below both way

1. using Management Class


C#
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#

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

What I have tried:

Please check above Code for management class and Power Shell,
I tried these both, but still is not solved
Posted
Updated 12-Sep-19 6:38am
Comments
Richard MacCutchan 12-Sep-19 11:13am    
Are you running this application as Administrator?
Varun Nayak89 12-Sep-19 12:32pm    
@Richard, I just Run my Application as an administrator and Boom. Problem solved!!
can you write the same thing inside solution I want to mark as an answer
Richard MacCutchan 12-Sep-19 12:38pm    
See below.

1 solution

The application must run as Administrator. You can automate this by adding a manifest file to your application containing the following settings:
<!-- set Execution level -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  <security>
    <requestedPrivileges>
      <requestedExecutionLevel
          level="requireAdministrator" <!-- request admin privileges -->
          uiAccess="false"
      />
    </requestedPrivileges>
  </security>
</trustInfo>


See also running-application-as-an-administrator-when-user-is-administrator[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900