0

Apologies for this mess, I started a few days ago and I'am still trying to learn. My code :

private void button1_Click(object sender, EventArgs e)
        {
            ManagementScope oMs = new ManagementScope();
            ObjectQuery oQuery =
                new ObjectQuery("Select * From Win32_NetworkAdapter");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();
            foreach (ManagementObject oReturn in oReturnCollection)
            {
                if (oReturn.Properties["NetConnectionID"].Value != null)
                {
                    // I want the result from this pasted into the "Network Adapter" prompt           
                    Console.WriteLine(oReturn.Properties["NetConnectionID"].Value);
                    // This is probably 100% wrong, sorry.
                    String NetworkAdapter = Console.WriteLine(oReturn.Properties["NetConnectionID"].Value);

                    Process process = new Process();
                    process.StartInfo.FileName = "cmd.exe";
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardInput = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.UseShellExecute = false;
                    process.Start();
                    // I want to insert the Name of a network adapter into this command prompt, but I can't seem to manage it.
                    process.StandardInput.WriteLine("netsh interface ipv4 set dns "NetworkAdapter" static 8.8.8.8");
                    process.StandardInput.WriteLine("netsh interface ipv4 add dns "NetworkAdapter" 8.8.4.4 index=2");
                    process.StandardInput.Flush();
                    process.StandardInput.Close();
                    process.WaitForExit();
                    Console.WriteLine(process.StandardOutput.ReadToEnd());
                    Console.Read();
                }
            }
       }

The idea is that when I press the button, it will detect my active Network Adapter name and paste it into standard dns change through cmd.exe prompt. I'm starting to think I've made it harder for myself than it has to be.

Thank you for any help.

Kaj
  • 806
  • 6
  • 16
Rookie89
  • 3
  • 3
  • To save the adapter, All you have to do is : string adapter = oReturn.Properties["NetConnectionID"].Value; then add it to ur string in cmd – Kaj Jun 08 '18 at 21:41
  • @kaj I tried String NetworkAdapter = oReturn.Properties["NetConnectionID"].Value; together with process.StandardInput.WriteLine(@"netsh interface ipv4 set dns "+NetworkAdapter+" static 8.8.8.8"); process.StandardInput.WriteLine(@"netsh interface ipv4 add dns "+NetworkAdapter+" 8.8.4.4 index=2"); but I'am getting the following: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast? – Rookie89 Jun 08 '18 at 21:50
  • That's the way you get the string and pass it as a parameter. What's ur question though ? – Kaj Jun 08 '18 at 21:50
  • I can't seem to get it to work. The console shows that it only tries to run "netsh interface ipv4 set dns" and cuts off there. So I guess my question would be what am I doing wrong? – Rookie89 Jun 08 '18 at 21:59
  • Look at the answer below – Kaj Jun 08 '18 at 22:06

1 Answers1

0

The short version to change the dns :

First get the network adapter :

public static NetworkInterface GetActiveEthernetOrWifiNetworkInterface()
{
    var Nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
        a => a.OperationalStatus == OperationalStatus.Up &&
        (a.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || a.NetworkInterfaceType == NetworkInterfaceType.Ethernet) &&
        a.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily.ToString() == "InterNetwork"));

    return Nic;
}

then to set DNS :

public static void SetDNS(string DnsString)
{
    string[] Dns = { DnsString };
    var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface();
    if (CurrentInterface == null) return;

    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();
    foreach (ManagementObject objMO in objMOC)
    {
        if ((bool)objMO["IPEnabled"])
        {
            if (objMO["Caption"].ToString().Contains(CurrentInterface.Description))
            {
                ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                if (objdns != null)
                {
                    objdns["DNSServerSearchOrder"] = Dns;
                    objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
                }
            }
        }
    }
}

then to use the method like :

SetDNS("127.0.0.1");

to unset the dns use :

public static void UnsetDNS()
{
    var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface();
        if (CurrentInterface == null) return;

    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();
    foreach (ManagementObject objMO in objMOC)
    {
        if ((bool)objMO["IPEnabled"])
        {
            if (objMO["Caption"].ToString().Contains(CurrentInterface.Description))
            {
                ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                if (objdns != null)
                {
                    objdns["DNSServerSearchOrder"] = null;
                    objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
                }
            }
        }
    }
}
Kaj
  • 806
  • 6
  • 16
  • Thanks a bunch! This solves it in a much better way than command prompts! Thanks again! – Rookie89 Jun 08 '18 at 22:10
  • A quick followup question: To add a secondary DNS, like google uses 8.8.8.8 + 8.8.4.4 - How do I approach this? Also placing UnsetDNS(); as a button1 should set it to DHCP? Thanks again! – Rookie89 Jun 08 '18 at 22:30
  • To set a secondary DNS , you could pass an array to the method contains two ip's like : string[] both = { "127.0.0.1", "127.0.0.2" }; or split them by any marker and then convert it to an array like this line : string[] Dns = { DnsString }; Here it's converting the string to an array, simply make it like : string[] Dns = DnsString.Split('*'); and you'll set two DNS – Kaj Jun 08 '18 at 23:33