I want to list up all printers connected to my network (including not installed)
I could manage to get all IP addresses of connected devices to my PC, by ping to all the addresses on gateway. And then I obtained Host name by
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
return entry.HostName;
I noticed that printers does not have a Host name.
Now I need to figure out which IP's belongs to a printer of my IP list or mac address.
how can i do that.
When we install a network printer, Windows is listing the names of printers. Can we obtain the such name using IP or MAC?
Include System.Management with
using System.Management;
foreach (string printername in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printername);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
}
And you will get all the info of every printer, including name and IP
If you want to get the printer IP from the name just use
If(printer.Properties.Caption.Contains("Printer name")
{
return printer.Properties.PortName;
}
Otherwise, to obtain the ip from the name, reverse the process and search for the ip and return the name.
For printers in the network, try this:
using System.Management;
private void Form1_Load(object sender, EventArgs e)
{
System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");
System.Management.ManagementObjectSearcher mosearcher = new
System.Management.ManagementObjectSearcher(oquery);
System.Management.ManagementObjectCollection moc =
mosearcher.Get();
foreach (ManagementObject mo in moc)
{
System.Management.PropertyDataCollection pdc = mo.Properties;
foreach (System.Management.PropertyData pd in pdc)
{
if ((bool)mo["Network"])
{
MessageBox.Show(String.Format("{1}", mo[pd.Name]));
}
}
}
}
// To list printers installed on computer online/offline
Code Snippet
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
MessageBox.Show(printer);
}
Related
Reading RFID's Physical Device Object Name through Serial Port using WMI in C#
I'm setting up a C# code to read signals from different RFID readers. So, I want to get Physical Device ID to recognize which device is sending which signal. So I'm trying to read device information through WMI which has more than 13xx classes.
code.
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
ManagementObjectCollection objCollection = objSearcher.Get();
foreach (ManagementObject obj in objCollection)
{
string info = "HardwareID : "+obj["HardwareID"];
}
I expected the information of each RFID reader unique physical ID.
HardwareID is a string[] and not a string so to obtain is you have to do something like this
var objSearcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
var objCollection = objSearcher.Get();
foreach (var queryObj in objSearcher.Get())
{
Console.WriteLine("Name {0}" , queryObj["Name"]);
if (queryObj["HardwareID"] == null)
Console.WriteLine("HardwareID: {0}", queryObj["HardwareID"]);
else
{
var arrHardwareID = (String[])(queryObj["HardwareID"]);
foreach (var arrValue in arrHardwareID)
{
Console.Write("HardwareID: {0}\t", arrValue);
}
}
}
Also, you can always use any NuGet package to ease your work like Kexla or ORMi
I am trying to retrieve the MAC address for the onboard ethernet adapter from a computer, in order to generate a unique identifier for the device. Below is the approach I am using.
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
}
However, the Bluetooth adapter, VM adapter and several other network adapters are also of the NetworkInterfaceType.Ethernet type. How can I specifically get the onboard ethernet connection's MAC address?
Doing a contains to omit those wouldn't be possible. Any help would be much appreciated.
I recently wrote a Powershell Script to generate a permanent system-format-immutable unique ID for a Windows PC for inventory purposes (QR encode the ID, print it on a sticker...).
It concatenates the PC manufacturer UUID field with the permanent MAC address of every PCI-connected network adapter (sorted alphabetically by MAC). The PCI requirement automatically dismisses removable or virtual NICs. The real script MD5-hashes the resulting string in order to obtain a more homogeneous identifier (constant length and 0-9A-F set of symbols), but I will omit this here for the sake of simplicity
I could’ve settled for the PC manufacturer UUID and call it a day, but I didn’t feel comfortable with an ID that relies on:
Each PC manufacturer in the world making the effort of filling in the UUID BIOS field.
Every PC manufacturer making the effort of keeping track of already used UUIDs
Basically, I tried to adhere to the intuitive idea of putting in the mixer as many non-removable components with permanent and “unique” (dream on) identifier as possible.
This ID generation technique is not fail proof: if a new PCI network adapter is added to the system, the ID will change. But with the popularization of integrated NICs I believe this is no longer something to worry about, if it ever was.
This solution is not directly applicable for C#, but I believe it can be easily adapted since Powershell shares almost the same .net object-class ecosystem.
#Variable names in spanish, but if I try to translate them in a hurry
#I will most certainly end up with a non-working script
$elpc=(Get-WmiObject -Class Win32_ComputerSystemProduct)
$id=$elpc.UUID #This is the UUID the manufacturer wrote somewhere in the BIOS
#Get network devices
#"Net" for network devices, "PCI*" because PCI connected devices begin that way
$dispositivosdered=#(Get-PnpDevice | Where-Object {($_.Class -eq "Net") -and ($_.InstanceId -like "PCI*")})
#Get network adapters
#Use "PermanentAddress" property. "MacAddress" property can be spoofed easily
$tarjetasdered=#(Get-Netadapter | Sort-Object PermanentAddress)
#Double loop to rule out any network adapters which are not PCI
#Comparison is made using long name, ie "Realtek PCIe GBE Family Controller #2"
#Is the only valid field I found to (inner) join the device and adapter worlds
for($j=0; $j -lt $tarjetasdered.length; $j++) {
for ($i=0; $i -lt $dispositivosdered.length; $i++) {
if($dispositivosdered[$i].FriendlyName -eq $tarjetasdered[$j].InterfaceDescription) {
if(-not [string]::IsNullOrEmpty($tarjetasdered[$j].PermanentAddress)) {
$id= $id + $tarjetasdered[$j].PermanentAddress.Replace("-", "");
}
}
}
}
As an option (not the best, but still =) ) - You can try to use
metric. In most cases the metric of the network to a physical network
card priority
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (!(mo["Description"].ToString().Contains("VM")))
{
if (!(mo["Description"].ToString().Contains("Virtual")))
{
if (!(mo["Description"].ToString().Contains("Hyper")))
{
string[] addresses = (string[])mo["IPAddress"];
string IPConnectionMetric = Convert.ToString(mo["IPConnectionMetric"]).Trim();
foreach (string ipaddress in addresses)
{
listBox1.Items.Add(ipaddress + ";" + IPConnectionMetric);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count > 1)
{
int maximum = int.MinValue;
int minimum = int.MaxValue;
for (int i = 0; i < listBox1.Items.Count; i++)
{
int output = Convert.ToInt32(listBox1.Items[i].ToString().Split(';')[1]);
if ((int)output > maximum)
maximum = (int)output;
}
for (int i = 0; i < listBox1.Items.Count; i++)
{
int output = Convert.ToInt32(listBox1.Items[i].ToString().Split(';')[1]);
if ((int)output < maximum)
minimum = (int)output;
if (listBox1.Items[i].ToString().Contains(minimum.ToString()))
{
var minmetric = listBox1.Items[i].ToString();
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
foreach (UnicastIPAddressInformation ip in net.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ip.Address.ToString().Contains(minmetric.ToString().Split(';')[0]))
{
var ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
else
{
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
var ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
}
using system.Management;
private string GetMACAddress()
{
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(":", "");
return MACAddress;
}
I am very new to embedded programming, I am tryig to get all port names in a list. I guess this is the most basic operation.
using System.IO.Ports;
string[] ports = SerialPort.GetPortNames();
Not sure where I am going wring with this basic operation, but the string is empty. Any leads to what i am doing wrong would be helpful
GetPortNames will only gather valid connected COM ports.
If you are trying to gather the COM port for a disconnected port you will need to search through the registry. Here's how I find the correct device I want based off VID and PID.
public class ComPortFinder
{
public static List<DeviceInfo> FindConnectedDevices(uint vid, uint pid)
{
string pattern = string.Format("^VID_{0:X4}.PID_{1:X4}", vid, pid);
Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
List<DeviceInfo> devices = new List<DeviceInfo>();
RegistryKey rk1 = Registry.LocalMachine;
RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");
foreach (String s3 in rk2.GetSubKeyNames())
{
RegistryKey rk3 = rk2.OpenSubKey(s3);
foreach (String s in rk3.GetSubKeyNames())
{
if (_rx.Match(s).Success)
{
RegistryKey rk4 = rk3.OpenSubKey(s);
foreach (String s2 in rk4.GetSubKeyNames())
{
RegistryKey rk5 = rk4.OpenSubKey(s2);
RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
if (!string.IsNullOrEmpty((string)rk6.GetValue("PortName")))
{
DeviceInfo di = new DeviceInfo()
{
VenderId = vid,
ProductId = pid,
SerialNumber = "UNKNOWN",
ComPort = rk6.GetValue("PortName").ToString()
};
devices.Add(di);
}
}
}
}
}
return devices;
}
}
public struct DeviceInfo
{
public uint VenderId;
public uint ProductId;
public string SerialNumber;
public string ComPort;
}
I do not take credit for this, as I believe this was stolen from another StackOverflow answer but hopefully it will help.
According to Juanma's answer you can get all ports by using wmi instruments in here How to find available COM ports?
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("PortName: {0}", queryObj["PortName"]);
//If the serial port's instance name contains USB
//it must be a USB to serial device
if (queryObj["InstanceName"].ToString().Contains("USB"))
{
Console.WriteLine(queryObj["PortName"] + "
is a USB to SERIAL adapter/converter");
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
don't forget to add System.Management reference
I want to develop an application which can list all the connected devices to my wifi network and their RSSI values.Could some one tell me how to approach this.Any sample codes would be of help and preferabbly in c sharp.Thanks.
using System.DirectoryServices;
...
List<String> _ComputerNames = new List<String>();
String _ComputerSchema = "Computer";
DirectoryEntry _WinNTDirectoryEntries = new DirectoryEntry("WinNT:");
foreach (DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children)
{
foreach (DirectoryEntry _PCNameEntry in _AvailDomains.Children)
{
if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower()))
{
_ComputerNames.Add(_PCNameEntry.Name);
}
}
}
This code lists the connected devices but how to get the RSSI value of these devices.
May be the title is duplicate. I am getting HDD of the laptop serial number successfully when no USB devices are connected. But when any USB is connected, the code gets the serial number of connected device. I only want the serial number of HDD of laptop or desktop even though USBs are connected.
Below is the code.
using System.Management;
namespace SystemInfo
{
public class Info1
{
public static String GetHDDSerialNo()
{
ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection mcol = mangnmt.GetInstances();
string result = "";
foreach (ManagementObject strt in mcol)
{
result += Convert.ToString(strt["VolumeSerialNumber"]);
}
return result;
}
}
}
try this
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
foreach (ManagementObject currentObject in theSearcher.Get())
{
ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());
}
You can use WMI Win32_DiskDrive, filter on MediaType containing "fixed" and get the SerialNumber
Something like :
public static String GetHDDSerialNo()
{
ManagementClass mangnmt = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection mcol = mangnmt.GetInstances();
string result = "";
foreach (ManagementObject strt in mcol)
{
if (Convert.ToString(strt["MediaType"]).ToUpper().Contains("FIXED"))
{
result += Convert.ToString(strt["SerialNumber"]);
}
}
return result;
}
Media type can contain "External", "Removable", "fixed". Exact string depends on OS. On Seven and XP, that String can be different. That's why we use Contains.
little reading