Get list of installed printers using C# WMI

Well, almost about an year back I write an application which search for the available printer on the server and do some operation accordingly. Today while browsing my code library I found that small test application. So I thought it would be good to share this with the community.

Management Objects are really good, I mean when it comes to windows you can do lots of operations using Management Object. You can get the list of services installed on system, hardware and etc. And the point which is worth to mention here is you can do that by using simple query like TSQL.

To access the printer information on the local machine you can use the following code

   1:             ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
   2:             objScope.Connect();
   3:            
   4:             SelectQuery selectQuery = new SelectQuery();
   5:             selectQuery.QueryString = "Select * from win32_Printer";
   6:             ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
   7:             ManagementObjectCollection MOC = MOS.Get();
   8:             foreach (ManagementObject mo in MOC)
   9:             {
  10:                 listBox1.Items.Add(mo["Name"].ToString().ToUpper());
  11:             }

 

The above code will use the current logged on identity as the default credentials. where as following code will get the list of printer installed from a remote location.

   1: ConnectionOptions objConnection = new ConnectionOptions();
   2: objConnection.Username = "aghausman";
   3: objConnection.Password = "nightmare";
   4: objConnection.Authority = "ntlmdomain:DDI"; //Where DDI is the name of my domain
   5: // Make sure the user you specified have enough permission to access the resource. 
   6:  
   7:  
   8: ManagementScope objScope = new ManagementScope(@"\\10.0.0.4\root\cimv2",objConnection); //For the local Access
   9: objScope.Connect();
  10:  
  11: SelectQuery selectQuery = new SelectQuery();
  12: selectQuery.QueryString = "Select * from win32_Printer";
  13: ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
  14: ManagementObjectCollection MOC = MOS.Get();
  15: foreach (ManagementObject mo in MOC)
  16: {
  17:     listBox1.Items.Add(mo["Name"].ToString().ToUpper());
  18: }

 

and here is the attachment of the solution files created in Visual Studio 2008

No Comments