I'm a c# newby who want to learn more about programming. So I started with a simple tool, wich can set the address of a choosen network adapter to static or dynamic (like the Windows TCP/IP Properties. I set the tool's design exactly like the TCP/IP Properties).
Setting a static IP address to the network adapter works pretty good.
But when I disconnet the Computer form the network and then set the network adapter's IP to dynamic (Obtain an IP address automatically"), it won't set the Windows IP Propertie to dynamic. I'm totaly lost with this problem, I have no idea how to solve it.
I understand that I only get an IP address automatically, when I'm connected to a network (where a router or a DHCP server is enabled).
But when I disconnect the computer form the network, an I set the IP Properties to dynamic with the the Windows TCP/IP Properties, it works well. What is worng in my code?
Thanks a lot for your help!
Below the code I'm using:
public void setDHCPMode()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["ipEnabled"])
continue;
try
{
string desc = (string)(mo["Description"]);
if (desc == NICcomboBox.Text)
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
toolStripStatusLabel1.Text = "DHCP set";
}
catch (Exception ex)
{
MessageBox.Show("Unable to set DHCP : " + ex.Message);
}
}
}
I found the problem. It looks like the WMI dosn't work correctly. It's impossible to set the TCP/IP Properties to DHCP, while the cable is unplugged for the specific NIC.
I solved it, through setting DHCP mode in the regestry. Now it works perfectly.
Related
I have 3 wifi at my home, in some rooms I have signal from the 3 routers and If I'm connected to one windows 10 won't change to the strongest wifi. I would like to know a working way to disable and enable wifi that works in windows 10.
My code doesn't work in widnows 10.
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
I'm testing Native Wifi with some success, I'll post more results soon
How do I get the port details of the Bluetooth device that I have paired within my windows form c# application?
Manually I can get all port names but I need the com port name that allocated to particular Bluetooth Device.
Check this post
the Win32_PnPEntity is Plug and play devices MSDN
you can go on the drivers also to find your device
// The WMI query
const string QueryString = "SELECT * FROM Win32_PnPSignedDriver ";
SelectQuery WMIquery = new SelectQuery(QueryString);
ManagementObjectSearcher WMIqueryResults = new ManagementObjectSearcher(WMIquery);
// Make sure results were found
if (WMIqueryResults == null)
return;
// Scan query results to find port
ManagementObjectCollection MOC = WMIqueryResults.Get();
foreach (ManagementObject mo in MOC)
{
if (mo["FriendlyName"] != null && mo["FriendlyName"].ToString().Contains("YOUR_DEVICE_NAME"))
{}
//Check the mo Properties to find the COM port
}
How can I disable/enable an internet connection? Just want to disable internet connection only not LAN.
I tried this but it is not working
string[] connections = DisconnectWrapper.Connections();
for (int i = 0; i < connections.Length; i++)
{
try
{
DisconnectWrapper.CloseConnection(connections[i]);
}
catch (Exception ex)
{ }
}
You can use WMI.
Add System.Management to your referenced and try this code
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
There is another article:Disable/Enable Network Connections Programmatically.
with WMI you can disable and enable all network connections.
Edited:
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_NetworkAdapter"))
{
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject obj in results)
{
System.Console.WriteLine("Found adapter {0} :", obj["Caption"]);
System.Console.WriteLine("Disabling adapter ...");
object[] param = new object[0];
obj.InvokeMethod("Disable",param);
System.Console.WriteLine("Done.");
}
Console.ReadLine();
}
Be aware Some of the adapter cannot be disabled.
You can do what you need by doing a shell call to netsh.
Example:
netsh interface set interface "Target Adapter Name" enabled
netsh interface set interface "Target Adapter Name" disabled
Netsh will block so if you wait for the process you spawn to exit, you'll know it's done. It requires administrator privileges, so your process will also require it. Netsh will set its exit code to 0 on success or 1 on failure, so you can check that for feedback if needed.
I want to accesss the mac address of the computer using c#. I have used the following code to access mac address but there is some issue in this code.
Code 1
foreach( NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces() )
{
if( nic.OperationalStatus == OperationalStatus.Up )
{
Console.WriteLine( nic.GetPhysicalAddress().ToString() );
checkMAC = nic.GetPhysicalAddress().ToString();
break;
}
}
Code 2
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress = String.Empty;
foreach (ManagementObject mo in moc)
{
if (MACAddress == String.Empty) // only return MAC Address from first card
{
if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
}
mo.Dispose();
}
MACAddress = MACAddress.Replace(":", "");
In first code when we disconnected from network connection then it will return null mac address . second code return the mac address when network adapter connection id disconnected But when we disbled the network connection or remove the IP address of the computer then it will return the null mac address .
How to get the mac address when network connnection disabled, there is no IP address assigned to the PC or network connection disconnected?
When you disable your network adapter, you can't access it at all - it is as if it isn't installed, which is why you don't see a MAC address.
EDIT: Explanation:
A MAC address belongs to a network adapter. If you have 3 adapters you have 3 MAC addresses. If you have no adapters, you have no MAC address.
How am I able do find all local printers of the machine where the program is running with a user that doesn't have admin rights. I need to remap the printer IP and set the printer as default. My idea is to use impersonation to do this but I don't know where to find the printer and if it is a good solution to use impersonation.
Thanks for any help!
I don't think you will have any luck with this. Impersonation will not work here and just throw a exception. You can try this by making a impersonation and try to open Environment.Domain it should give you a exception.
You can try something like this without impersonation:
ManagementScope mscope = new ManagementScope(#"\root\CIMV2", options);
mscope.Connect();
System.Management.ObjectQuery oQuery = new ObjectQuery("Select * from Win32_TCPIPPrinterPort");
System.Management.ManagementObjectSearcher searcher = new ManagementObjectSearcher(mscope, oQuery);
ManagementObjectCollection moCollection = searcher.Get();
foreach (ManagementObject mo in moCollection)
{
string name = mo["Name"].ToString();
if (name.Equals(this.portName))
{
System.Threading.Thread.Sleep(10000);
mo["HostAddress"] = this.printerIP;
mo.Put();
Console.WriteLine("Adjusted Printer Port to new IP address " + this.printerIP);
return true;
}
}