I want to change NETWORK CONFIGURATION programmatically. Everything is working fine, only IP of DNS doesn't want to change, it stays empty.
I use next code to change configuration:
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 you are using the System.Net.NetworkInformation.NetworkInterface you'll need to change this line to if (objMO["Caption"].ToString().Contains(NIC)) and pass in the Description property instead of the name
//if (objMO["Caption"].Equals(NIC))
if (objMO["Caption"].ToString().Contains(NIC))
{
try
{
ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split('.');
ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception)
{
throw;
}
}
}
}
}
If you only have one DNS IP address, you need assign the value as
newDNS["DNSServerSearchOrder"] = new string[]{DNS};
If you have two DNS IP addesses and they are separated by ';', you need assign the value as
newDNS["DNSServerSearchOrder"] = DNS.Split(';');
The input value must be a string array.
Related
I am having quite some difficulty connecting a specific, existing network adapter to an existing switch. I can create a new network adapter and connect it to my VM through several examples posted online but cannot make that extra step. The following function finds my network adapter and executes without error, but does not otherwise make the connection. Any assistance is greatly appreciated!
**EDIT: Solved, see code below.**
Solved:
public static void ConnectInterfaceToSwitch(string VmName, string networkInterfaceName, string switchName)
{
ManagementScope scope = new ManagementScope(#"root\virtualization\v2");
ManagementObject mgtSvc = WmiUtilities.GetVirtualMachineManagementService(scope);
ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope);
ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(VmName, scope);
ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine);
ManagementObjectCollection portsSettings = virtualMachineSettings.GetRelated("Msvm_SyntheticEthernetPortSettingData", "Msvm_VirtualSystemSettingDataComponent", null, null, null, null, false, null);
{
foreach (ManagementObject portSettings in portsSettings)
{
if (portSettings["ElementName"].Equals(networkInterfaceName))
{
Console.WriteLine("Adapter found: " + networkInterfaceName);
ManagementObjectCollection connections = portSettings.GetRelated("Msvm_EthernetPortAllocationSettingData");
foreach (ManagementObject connection in connections)
{
connection["HostResource"] = new string[] { ethernetSwitch.Path.Path };
connection["EnabledState"] = 2; // 2 means "Enabled"
ManagementBaseObject inParams = mgtSvc.GetMethodParameters("ModifyResourceSettings");
inParams["ResourceSettings"] = new string[] { connection.GetText(TextFormat.WmiDtd20) };
ManagementBaseObject outParams = mgtSvc.InvokeMethod("ModifyResourceSettings", inParams, null);
WmiUtilities.ValidateOutput(outParams, scope);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Connected VM '{0}' to switch '{1}'.", VmName, switchName));
}
}
}
}
}
I wrote an application using a webservice and I want to simulate a network failure for test purposes. I know I could turn off the network manually, but it would be awesome if it would be automatically.
I tried the solution from: How to simulate network failure for test purposes (in C#)? from Larsenal but it doesn't recognize the ManagementClass/ObjectCollection/... and I don't know why (i used System.Managment.Man... and it still didn't work. I imported the required references - didn't work. I have no idea what I am doing wrong)
It should work something like this:
[TestMethod]
public void Service_Login_NoInternetConnection()
{
// Some code...
TurnOffNetworkConnection();
// More code...
TurnOnNetworkConnection();
// Blablabla code...
}
You can use WMI for it.
First make sure you add reference : System.Management
Then I get all devices with :
"ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");"
Now i need to check if a device got DHCPLeaseObtained.
So I use foreach to check every network device in the searcher :
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
If the device has no DHCPLeaseObtained the string will be emty.
So I check if the string is emty :
if (String.IsNullOrEmpty(Check))
Then you can use ReleaseDHCPLease and RenewDHCPLease in the else.
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
or
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
using System.Management;
public void TurnOnNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
public void TurnOffNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
i have a windows application which insert client machine's default printer to database on application launch. It works perfectly in my solution. I use the following code to save this.
string GetDefaultPrinter()
{
string defaultprinter = "";
try
{
PrinterSettings settings = new PrinterSettings();
foreach (string printer in PrinterSettings.InstalledPrinters)
{
settings.PrinterName = printer;
if (settings.IsDefaultPrinter)
{
defaultprinter = printer;
string[] array_printer= defaultprinter.Split('\\');
defaultprinter= array_printer[3].ToString();
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", defaultprinter);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject localprinter in coll)
{
foreach (PropertyData property in localprinter.Properties)
{
// Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
//MessageBox.Show(property.Name+"-"+ property.Value);
if (property.Name == "ShareName")
{
defaultprinter = property.Value.ToString().Trim();
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("defaltprinter- "+defaultprinter+"-" + ex.Message);
}
return defaultprinter;
}<br>
If I host this application in citrix, then what should I do to perform the same function?
regards,
Sivajith S.
I have a problem with set Ipv6 in windows.
The below code can set a IPv4 address but I can't try to set IPv6.
Please help me.
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
try
{
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
// Make sure this is a IP enabled device. Not something like memory card or VM Ware
if ((bool)mo["IPEnabled"])
{
if (mo["Caption"].Equals(nicName))
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newGate["DefaultIPGateway"] = new string[] { Gateway };
newGate["GatewayCostMetric"] = new int[] { 1 };
newIP["IPAddress"] = IpAddresses.Split(',');
newIP["SubnetMask"] = new string[] { SubnetMask };
newDNS["DNSServerSearchOrder"] = DnsSearchOrder.Split(',');
ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGate, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
break;
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
I also tried to set a fixed IPv6 address via WMI, but it does not appear to work (the IPv4 address does work).
The only way I found to do this is by starting netsh from within the code, and using it to set the fixed (static) IPv6 address. If anyone has a more elegant solution, I will happily use it. Meanwhile:
Use the .NET System.Diagnostics.Process class to start a netsh process.
The netsh command reference, which tells you the parameters that you need, is here.
I found that I needed to start a new netsh process for each command that I sent.
For each netsh process, I created a handler for the process's OutputDataReceived event, that logged the netsh feedback.
I am writing an application to change the IP addresses of local and remote machines using WMI. This code successfully changes the gateway and DNS of the remote machine and the same code (in a different class and minus the management scope part) changes all of the data (the two IPs, gateway, DNS) locally. The problem is it doesn't change the remote IP address. Please can someone advise as I have looked everywhere for this answer?
I have tested on windows 7 and xp with no firewalls and with .net 4 installed on remote machines
class remoteIPChange
{
public string setTillIP(string IPAddress1, string IPAddress2, string SubnetMask, string Gateway)
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope(
"\\\\"+IPAddress1+"\\root\\CIMV2", connection);
scope.Connect();
ObjectGetOptions o = new ObjectGetOptions();
ManagementPath p = new ManagementPath("Win32_NetworkAdapterConfiguration");
ManagementClass objMC = new ManagementClass(scope,p,o);
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
ManagementBaseObject objNewDNS = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] { Gateway };
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] { IPAddress1, IPAddress2 };
objNewIP["SubnetMask"] = new string[] { SubnetMask, SubnetMask };
//Set DNS servers
objNewDNS["DNSServerSearchOrder"] = new string[] {Gateway };
//Invoke all changes
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);
return ("Updated IPAddress to " + IPAddress + ", \nSubnetMask to " + SubnetMask + " \nand Default Gateway to " + Gateway + "!");
}
catch (Exception ex)
{
return ("Unable to Set IP : " + ex.Message);
}
}
return "code has not run";
}
}
I would check the ReturnValue from the invokemethod on EnableStatic. I am pretty sure passing in a null for your subnet is your problem. Provide a valid array of subnets that match your ip addresses instead of that null.