Search code examples
c#ip-addressstatic-ip-address

set blank ip address or remove ip adddress


I want to set ip address, subnet, gateway & dns; there is no issue in setting up but once the ip address is applied i'm trying to delete the existing gateway, pref dns its not working.

I tried to send a empty string but its always picking up .... (4dots) instead of empty string.

How can i set empty ip address or delete the gateway & pref dns ipaddress using the below method?

Get ip address from textbox usercontrol:

string[] pdns = ipsefpredns.GetIPaddress();
string str_pdns = pdns[0].ToString() + "." + pdns[1].ToString() + "." + pdns[2].ToString() + "." + pdns[3].ToString();
string ipaddressprefdns;
string emptypdns = pdns[0].ToString() + pdns[1].ToString()  + pdns[2].ToString()  + pdns[3].ToString(); 

if (pdns == null || pdns.Length ==0) //if the array is empty,null get empty string
{
    
    ipaddressprefdns = emptypdns;
    
}
else
{
    ipaddressprefdns = str_pdns;

}

Method to apply ipaddress:

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "netsh");
Process.Start(new ProcessStartInfo(fileName)
{
    Arguments = string.Format("interface ip set address \"{0}\" static {1} {2} {3}", nicname, ipaddressstatic, ipaddresssubnet, ipaddressgateway),
    CreateNoWindow = true,
    WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();
Process.Start(new ProcessStartInfo(fileName)
{
    Arguments = string.Format("interface ip set dns \"{0}\" static {1} Primary", nicname, ipaddressprefdns),
    CreateNoWindow = true,
    WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();

Solution

  • I found a solution by reading the array then compare withit, pass none to gateway address.

    string[] pdns = ipsefpredns.GetIPaddress();
    string str_pdns = pdns[0].ToString() + "." + pdns[1].ToString() + "." + pdns[2].ToString() + "." + pdns[3].ToString();
    string ipaddressprefdns="";
    string prefdnss = UsingLoopStringBuilder(pdns);
    if (!String.IsNullOrEmpty(prefdnss))
    {
        ipaddressprefdns = str_pdns;
    }
    else
    {
        ipaddressprefdns = "none";
    }
    
    //method to read string array[]
    public string UsingLoopStringBuilder(string[] array)
    {
        var result = new StringBuilder();
        foreach (var item in array)
        {
            result.Append(item);
        }
        return result.ToString();
    }