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
{
var newGateway = adapter.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
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}";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
var results = pipeline.Invoke();
runspace.Close();
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