Listing network printers - c#

Trying to run the following (found here http://www.encodedna.com/2013/04/show-printers-using-wmi.htm ) to get a list of network printers but it only returns printers added to my machine
System.Management.ManagementScope objMS = new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
if (Convert.ToBoolean(Printers["Local"])) // LOCAL PRINTERS.
{
Console.WriteLine("Local :- " + Printers["Name"]);
}
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
Console.WriteLine("Network :- " + Printers["Name"]);
}
}
I can view/add network printers in control panel. Just curious why it isn't showing them. Any thoughts?
Thanks!

Try:
foreach (string printerString in PrinterSettings.InstalledPrinters)
{
// do something
}

Related

C# Trying to get the printer status when it is offline

I need to get the printer status when it is offline, below is how I am getting the status;
// Set management scope
ManagementScope scope = new ManagementScope(#"\root\cimv2");
scope.Connect();
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer["Name"].ToString();
if (printerName.Equals(#"TEC B-EV4-T"))
{
//Console.WriteLine("Printer = " + printer["Name"]);
if (printer.Properties["PrinterStatus"].Value.ToString() == "7")
{
// printer is offline by user
MessageBox.Show("TEC B-EV4-T is offline");
}
else
{
// printer is not offline
//Check API first then print
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(Environment.CurrentDirectory + "\\Report.rpt");
dialog.PrintQueue = new PrintQueue(new PrintServer(), "TEC B-EV4-T");
//to the data table here
//To data table
DataTable dt = ToDataTable(lotinstruct);
cryRpt.SetDataSource(dt);
cryRpt.PrintToPrinter(1, true, 0, 0);
//}
MessageBox.Show("Already save result please check label!");
}
}
}
The problem is here if (printer.Properties["PrinterStatus"].Value.ToString() == "7") it seems like the printer status is always 3 when I debug (printer status 3 means that it is idle 7 means that it is offline). Is there any way to find out if the printer TEC B-EV4-T is offline?
You can refer PrintQueue in built in .Net framework to check printer status. There are many properties in it to check different status:
string printerName = "TEC B-EV4-T";
var server = new LocalPrintServer();
PrintQueue queue = server.GetPrintQueue(printerName , Array.Empty<string>());
bool isOffline = queue.IsOffline;
bool isBusy = queue.IsBusy;
Don't use printer["PrinterStatus"]. You have to use printer["WorkOffline"] like below:
bool IsOffline = false;
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_Printer where Name='" + YourPrinter + "'");
foreach(ManagementObject printer in searcher.Get())
{
IsOffline = (bool)printer["WorkOffline"];
}
if (IsOffline)
{
...
}

How to get hard drive unique serial number in C#

I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.
private string getHardDiskID()
{
string hddID = null;
ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject strt in moc)
{
hddID += Convert.ToString(strt["VolumeSerialNumber"]);
}
return hddID.Trim().ToString();
}
But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...?
Thanks in advance..
You can try from this source:
As said in the source, a better solution is to get the Hard Drive Serial Number given by the Manufacturer. This value won't change even if you format your Hard Drive.
searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in searcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
ManagementObjectSearcher searcher;
searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
string serial_number="";
foreach (ManagementObject wmi_HD in searcher.Get())
{
serial_number = wmi_HD["SerialNumber"].ToString();
}
MessageBox.Show(serial_number);
Check below code to get HDD Serial
ManagementObjectSearcher objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in objSearcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
Also You can type "wbemtest" in windows run. WBEMTEST is tool which
helps in running WQL queries.

Get client machine's default printer when application is accessed through citrix

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.

WMI: Get USB device description on insertion

How can I get a device Id and other description on insertion of USB device?
I've found an example how to get notified about USB device insertion/removal. But how to get device desrtiption info?
Here is my code snippet:
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = #"TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(USBRemoved);
w.Start();
}
... catch()....
UPDATE: Actually, it is a Serial COM device with USB connection. So there is no driveName property. How can I get USB description, which I can see in Device Manager? Does WMI provide this info with the notification about USB insertion?
Complete new answer according to your updated answer. You may check für any connected USB device:
ManagementScope sc =
new ManagementScope(#"\\YOURCOMPUTERNAME\root\cimv2");
ObjectQuery query =
new ObjectQuery("Select * from Win32_USBHub");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
ManagementObjectCollection result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["Description"].ToString());
if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["DeviceID"].ToString());
if (obj["PNPDeviceID"] != null) Console.WriteLine("PNPDeviceID:\t" + obj["PNPDeviceID"].ToString());
}
(see MSDN WMI tasks examples) for this)
or have a look into any COM ConnectedDevice
ManagementScope sc =
new ManagementScope(#"\\YOURCOMPUTERNAME\root\cimv2");
ObjectQuery query =
new ObjectQuery("Select * from Win32_SerialPort");
searcher = new ManagementObjectSearcher(sc, query);
result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["Caption"] != null) Console.WriteLine("Caption:\t" + obj["Description"].ToString());
if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["DeviceID"].ToString());
if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["PNPDeviceID"].ToString());
}
(see ActiveX Experts for further details on this)

How to get MAC ID of a system using C#

I am building a C# application and I want to fetch the MAC ID of the system. I have found many code snippets, but they either give wrong answers or throw exceptions. I am not sure which code snippet is giving the right answer. Can someone provide me the exact code snippet that fetches the MAC ID?
This will help you.
public string FetchMacId()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
and iterate through each interface, getting the MAC address for each one.
Another way would be to use management object:
ManagementScope theScope = new ManagementScope("\\\\computerName\\root\\cimv2");
StringBuilder theQueryBuilder = new StringBuilder();
theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
ManagementObjectCollection theCollectionOfResults = theSearcher.Get();
foreach (ManagementObject theCurrentObject in theCollectionOfResults)
{
string macAdd = "MAC Address: " + theCurrentObject["MACAddress"].ToString();
MessageBox.Show(macAdd);
}

Categories

Resources