I've been trying to implement the solution from this post: How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C# but for some reason it doesn't seem to work in my situation and I can't pinpoint the problem. I have this method:
public void SetDNS(string NIC, string DNS)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
if (objMO["Caption"].Equals(NIC))
{
ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split(',');
_ = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
System.Diagnostics.Debug.WriteLine("testing");
}
}
}
}
And then I call it like this SetDNS(objMO["Caption"].toString(), "192.168.7.2,8.8.8.8");
where objMO["Caption"]
is the NIC description of the current network adapter I want to configure. When I run the debug to test the program, nothing happens to the network adapter settings but in the debug output window "testing" does get printed out so I know that the method executed. Is there something obvious that I am missing here? I'm new to WPF and win32 so I apologize in advance if there is something I'm missing, thanks.
EDIT: When I checked the return value of SetDNSServerSearchOrder
it returned an error code of 91
which means Access Denied
. Does this mean I need elevation for the whole program and if so how do I achieve that?