Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Drawing.Printing;
- using System.Management;
- class Program
- {
- static void Main()
- {
- Console.WriteLine("Installed Printers and Their Details:\n");
- foreach (string printerName in PrinterSettings.InstalledPrinters)
- {
- Console.WriteLine($"Printer: {printerName}");
- string portName = GetPrinterPort(printerName);
- Console.WriteLine($" Port: {portName}");
- Console.WriteLine($" Type: {(IsVirtualPrinter(portName) ? "Virtual Printer" : "Physical Printer")}");
- PrintTrayDetails(printerName);
- Console.WriteLine(new string('-', 50));
- }
- }
- static void PrintTrayDetails(string printerName)
- {
- try
- {
- PrinterSettings settings = new PrinterSettings();
- settings.PrinterName = printerName;
- if (!settings.IsValid)
- {
- Console.WriteLine(" (Printer is not accessible)");
- return;
- }
- PrinterSettings.PaperSourceCollection paperSources = settings.PaperSources;
- Console.WriteLine($" Number of Trays: {paperSources.Count}");
- foreach (PaperSource tray in paperSources)
- {
- int capacity = GetTrayCapacity(printerName, tray.SourceName);
- Console.WriteLine($" - Tray: {tray.SourceName} (Kind: {tray.Kind}) - Capacity: {(capacity > 0 ? capacity + " sheets" : "Unknown")}");
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($" Error retrieving tray info: {ex.Message}");
- }
- }
- static string GetPrinterPort(string printerName)
- {
- try
- {
- string query = $"SELECT PortName FROM Win32_Printer WHERE Name = '{printerName.Replace("\\", "\\\\")}'";
- using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
- {
- foreach (ManagementObject printer in searcher.Get())
- {
- return printer["PortName"]?.ToString() ?? "Unknown";
- }
- }
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
- return "Unknown";
- }
- static int GetTrayCapacity(string printerName, string trayName)
- {
- try
- {
- string query = $"SELECT * FROM Win32_PrinterPaperTray WHERE PrinterName = '{printerName.Replace("\\", "\\\\")}'";
- using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
- {
- foreach (ManagementObject tray in searcher.Get())
- {
- if (tray["PaperTray"] != null && tray["PaperCapacity"] != null)
- {
- int capacity = Convert.ToInt32(tray["PaperCapacity"]);
- return capacity > 0 ? capacity : -1;
- }
- }
- }
- }
- catch
- {
- return -1; // Return -1 if information is unavailable
- }
- return -1;
- }
- static bool IsVirtualPrinter(string portName)
- {
- if (string.IsNullOrEmpty(portName)) return false;
- string[] virtualPorts = { "nul", "PORTPROMPT", "FILE:" };
- return Array.Exists(virtualPorts, p => portName.Equals(p, StringComparison.OrdinalIgnoreCase));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment