I want to judge if the computer running my program is in a certain network.
I have tried the code below
ManagementClass vNetworkAdapter = new ManagementClass("Win32_NetworkAdapter");
ManagementObjectCollection vNetworkAdapters = vNetworkAdapter.GetInstances();
foreach (ManagementObject vNetworkAdapterInfo in vNetworkAdapters)
{
string ID = (string)vNetworkAdapterInfo.Properties["NetConnectionID"].Value;
string Caption = (string)vNetworkAdapterInfo.Properties["Caption"].Value;
string Description = (string)vNetworkAdapterInfo.Properties["Description"].Value;
string SSID = (string)vNetworkAdapterInfo.Properties["DeviceID"].Value;
if (ID != null)
{
if (ID == "以太网")//judge certain type of connection by name, I only considered the wired and wireless connection
{
Console.WriteLine("以太网" + "\n" + Caption + "\n" + Description);
Console.WriteLine(SSID);
}
else if (ID == "WLAN")
{
Console.WriteLine("WLAN" + "\n" + Caption + "\n" + Description);
Console.WriteLine(SSID);
}
}
Console.WriteLine("");
}
It returns With
WLAN
[00000002] Killer(R) Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW)
Killer(R) Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW)
以太网
[00000003] Killer E2500 Gigabit Ethernet Controller
Killer E2500 Gigabit Ethernet Controller
But I not wanting this name, I want to get the name shown when we are connecting to a certain network(known as SSID for wireless connection), What I should do? thanks a lot!
Related
I am trying to show the vid/pid and the drive letter of a usb drive when I connect it to my computer. I'm actually able to do both, but not at the same time.
1: I can use Win32_DiskDrive to get to Win32_LogicalDisk and extract the drive letter. But the deviceId has a non-numerical pid/vid which I can't use.
2: I can use Win32_USBHub or Win32_PnPEntity to extract the vid/pid, but I can't find a link between them and the drive letter.
public void CheckForUsbDevice()
{
string text =
"SELECT * FROM __InstanceCreationEvent " +
"WITHIN 2 "
+ "WHERE TargetInstance ISA 'Win32_PnPEntity'";
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery(text);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
Console.ReadKey();
}
static readonly Guid GUID_DEVCLASS_USB = new Guid("{36fc9e60-c465-11cf-8056-444553540000}");
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if ((new Guid((string)instance["ClassGuid"]) == GUID_DEVCLASS_USB) && ((string)instance.Properties["Name"].Value == "USB Mass Storage Device"))
{
// we're only interested by USB devices, dump all props
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
}
}
This has the output:
Availability =
Caption = USB Mass Storage Device
ClassGuid = {36fc9e60-c465-11cf-8056-444553540000}
CompatibleID = System.String[]
ConfigManagerErrorCode = 0
ConfigManagerUserConfig = False
CreationClassName = Win32_PnPEntity
Description = USB Mass Storage Device
DeviceID = USB\VID_0911&PID_1F40&MI_00\6&27CAD51B&0&0000
ErrorCleared =
ErrorDescription =
HardwareID = System.String[]
InstallDate =
LastErrorCode =
Manufacturer = Compatible USB storage device
Name = USB Mass Storage Device
PNPClass = USB
PNPDeviceID = USB\VID_0911&PID_1F40&MI_00\6&27CAD51B&0&0000
PowerManagementCapabilities =
PowerManagementSupported =
Present = True
Service = USBSTOR
Status = OK
StatusInfo =
SystemCreationClassName = Win32_ComputerSystem
SystemName = WINDEV1905EVAL
I need a link between WMI classed containing the numerical pid/vid and the drive letter or a different way how that can be achieved.
I think it might be possible to use DeviceIoControl, but I have no idea where to start there.
Any help is highly appreciated.
I need to generate UUID for my Machine Mac address. Also i want extract the mac address from UUID.
I know we can use below two methods for encoding and decoding. But it will generate the encrypted string only not UUID.
Encode:
System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(plainTextBytes));
Decode:
System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(base64EncodedData));
But for my requirement i want to generate(encode) the UUID and extract(decode) the mac address . How to do this in C# code?
You can get the MAC address using the following code.
From our tests it will return null on about 1.3% of machines (probably some form of virtual machine or something very locked down).
MAC Address of first IP enabled device
public static string GetMACAddress()
{
try
{
using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
if (moc != null)
{
foreach (ManagementObject mo in moc)
{
try
{
Trace.WriteLine(mo["Index"] + " Mac " + mo["Caption"] + " : " + mo["MacAddress"] + " Enabled " + (bool)mo["IPEnabled"]);
if (mo["MacAddress"] != null && mo["IPEnabled"] != null && (bool)mo["IPEnabled"] == true)
{
return mo["MacAddress"].ToString();
}
}
finally
{
mo.Dispose();
}
}
}
}
}
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
}
return null;
}
I'm trying to find a particular USB device (1 or more) connected to my computer and retrieve the relevant path to the mounted drive. Ideally, it would be by finding the VID/PID of the USB device, but I'm not sure how to do that yet. The following works, but there must be some way to get the data in a single query.
What I'm doing here is looking or a physical drive that has a model matching HS SD Card Bridge USB Device and finding the physical drive # associated and using that to find the mounted partition..
foreach (ManagementObject disk in disks.Get()) {
//look for drives that match our string
Match m = Regex.Match(disk["model"].ToString(), "HS SD Card Bridge USB Device");
if (m.Success) {
m = Regex.Match(disk["DeviceID"].ToString(), #"PHYSICALDRIVE(\d+)");
if (m.Success) {
int driveNumber = Int32.Parse(m.Groups[1].ToString());
ManagementObjectSearcher mapping = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
foreach (ManagementObject map in mapping.Get()) {
m = Regex.Match(map["Antecedent"].ToString(), #"Disk #" + driveNumber + ",");
if (m.Success) {
string drive = map["Dependent"].ToString();
m = Regex.Match(drive, #"([A-Z]):");
if (m.Success) {
drive = m.Groups[1].ToString(); //< -- **FOUND**
}
}
}
//USBDevice dev = new USBDevice("", "");
// list.Items.Add();
Console.WriteLine("");
}
}
}
is there a way to do this from the VID/PID and a way to construct the search query so it requires just one query?
This is the one I used earlier . This will not be the answer. But will help you .
public int GetAvailableDisks()
{
int deviceFound = 0;
try
{
// browse all USB WMI physical disks
foreach (ManagementObject drive in
new ManagementObjectSearcher(
"select DeviceID, Model from Win32_DiskDrive where InterfaceType='USB'").Get())
{
ManagementObject partition = new ManagementObjectSearcher(String.Format(
"associators of {{Win32_DiskDrive.DeviceID='{0}'}} where AssocClass = Win32_DiskDriveToDiskPartition",
drive["DeviceID"])).First();
if (partition == null) continue;
// associate partitions with logical disks (drive letter volumes)
ManagementObject logical = new ManagementObjectSearcher(String.Format(
"associators of {{Win32_DiskPartition.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition",
partition["DeviceID"])).First();
if (logical != null)
{
// finally find the logical disk entry to determine the volume name - Not necesssary
//ManagementObject volume = new ManagementObjectSearcher(String.Format(
// "select FreeSpace, Size, VolumeName from Win32_LogicalDisk where Name='{0}'",
// logical["Name"])).First();
string temp = logical["Name"].ToString() + "\\";
// +" " + volume["VolumeName"].ToString(); Future purpose if Device Name required
deviceFound++;
if (deviceFound > 1)
{
MessageBox.Show(#"Multiple Removeable media found. Please remove the another device");
deviceFound--;
}
else
{
driveName = temp;
}
}
}
}
catch (Exception diskEnumerateException)
{
}
return deviceFound;
}
I have to change IP address very frequently for playing LAN games as well as for using internet at home. I am creating an application in C# which can do it quickly. I have made fields like Adapter Name, IP Address, Subnet, DNS Server Address.
My code which runs on set IP button click is below:
string adapter = comboAdapterName.Text;
string ip = comboIPAddress.Text;
string subnet = comboSubnet.Text;
string dns = comboDNS.Text;
Now I want to use this process method for taking data from those fields and append the string accordingly.
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();
But I guess it is not so easy. Because I am unable to edit this without disturbing the format. Also I tried creating a whole new string using many +s which i can place like:
ProcessStartInfo psi = new ProcessStartInfo(mystring);
But still it is too difficult for me. Please suggest an easy way to do this.
==========================================================================
I think I got it:
string ipstring = "netsh interface ip set address " + "\"" + adapter + "\"" + " " + "static" + " " + ip + " " + subnet + " " + dns;
You will need to use the String.Format method.
Example:
string subnet = comboSubnet.Text;
string formatted = string.Format("Subnet is: {0}", subnet);
MessageBox.Show(formatted);
Format that string to look like whatever you want.
You can get the current adapter config with following function:
private static void EthernetInf(out string ip, out string dns, out string nic) // To get current ethernet config
{
ip = "";
dns = "";
nic = "";
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (IPAddress dnsAdress in ni.GetIPProperties().DnsAddresses)
{
if (dnsAdress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
dns = dnsAdress.ToString();
}
}
foreach (UnicastIPAddressInformation ips in ni.GetIPProperties().UnicastAddresses)
{
if (ips.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !ips.Address.ToString().StartsWith("169")) //to exclude automatic ips
{
ip = ips.Address.ToString();
nic = ni.Name;
}
}
}
}
Following Function is used to set the IP in elevated command prompt:
private void SetIP(Button sender, string arg) //To set IP with elevated cmd prompt
{
try
{
if (sender.Background == Brushes.Cyan )
{
MessageBox.Show("Already Selected...");
return;
}
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.Verb = "runas";
psi.Arguments = arg;
Process.Start(psi);
if (sender == EthStatic || sender == EthDHCP )
{
EthStatic.ClearValue(Button.BackgroundProperty);
EthDHCP.ClearValue(Button.BackgroundProperty);
sender.Background = Brushes.Cyan;
}
if (sender == WIFIStatic || sender == WIFIDhcp)
{
WIFIStatic.ClearValue(Button.BackgroundProperty);
WIFIDhcp.ClearValue(Button.BackgroundProperty);
sender.Background = Brushes.Cyan;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This click button code passes the arguments to processstartinfo to set the IP
private void EthStatic_Click(object sender, RoutedEventArgs e)
{
SetIP(EthStatic, "/c netsh interface ip set address \"" + EthName + "\" static " + Properties.Settings.Default.EthIPac + " " + Properties.Settings.Default.Subnet + " " + Properties.Settings.Default.EthDnsac + " & netsh interface ip set dns \"" + EthName + "\" static " + Properties.Settings.Default.EthDnsac);
}
The complete app is available at:
https://github.com/kamran7679/ConfigureIP
I have code, which find my NIC card IP address, IP subnet, Gateway, Mac and network card name (description). But the problem is, I have multiple NIC cards and WiFi on my PC. And this program instead of 4 NIC cards shows me only one primary.
How can solve this problem ?
public void NIC_data()
{
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
string[] addresses = (string[])mo["IPAddress"];
string[] subnets = (string[])mo["IPSubnet"];
string[] defaultgateways = (string[])mo["DefaultIPGateway"];
textBox1.Text = string.Format("Network Card: {0}", mo["Description"]);
textBox2.Text = string.Format(" MAC Address: {0}", mo["MACAddress"]);
foreach (string ipaddress in addresses)
{
textBox3.Text = string.Format(" IP Address: {0}", ipaddress);
}
foreach (string subnet in subnets)
{
textBox4.Text = string.Format(" Subnet Mask: {0}", subnet);
}
foreach (string defaultgateway in defaultgateways)
{
textBox5.Text = string.Format(" Gateway: {0}", defaultgateway);
}
}
You just assign the last value of the loop to textBoxes like textBox3.Text = .....
either append to textBox3.Text += ... or use a combo box.