C# - Use WMI to get a list of all installed printers

  • 0 Replies
  • 155 Views

0 Members and 1 Guest are viewing this topic.

Offline Omega

    *
  • The Boss (Admin)
  • Black Hat Sec Member
  • Telegram: @BLACKHATSEC_FORUM
  • Posts: 190
  • Popularity: +1/-0
  • God of Malware
    • View Profile
    • Awards
« on: March 14, 2022, 09:26:25 AM »
C# - Use WMI to get a list of all installed printers

Code
// Snippet to retrieve the names of all installed printers on a machine. Can easily be modified to get other information such as port, driver, shared name, etc)
// Reference to Namespaces
System.Management
System.Collections.Generic

-------------------------------------------------------------

/// <summary>
/// method to populate a generic list holding all the available printers on a network
/// </summary>
/// <returns></returns>
public List<string> GetInstalledPrinters()
{
    List<string> printerList = new List<string>();

    try
    {
        //set the scope of this search to the local machine
        ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);
        //connect to the machine
        scope.Connect();

        //build the SelectQuery to pull from Win32_Printer
        SelectQuery query = new SelectQuery("select * from Win32_Printer");

        ManagementClass m = new ManagementClass("Win32_Printer");

        ManagementObjectSearcher obj = new ManagementObjectSearcher(scope, query);

        //now loop through what is found and populate our Generic list with
        //the names of all installed printers on the local machine
        using (ManagementObjectCollection printers = m.GetInstances())
            foreach (ManagementObject printer in printers)
                printerList.Add(printer["Name"].ToString());

        printerList.Sort();

        return printerList;
    }
    catch (Exception ex)
    {
        return null;
    }

}
  • Discord: BLACK HAT SEC#5222
  • [+]
  • [-]

  •