public List<string> WMIGetPrinterList(string pcname)
{
string query = "Select * from Win32_Printer";
pcname = CleanPCName(pcname);
StringBuilder queryResult = new StringBuilder();
List<string> resultList = new List<string>();
if (PcNameIsNotNullOrVoid(pcname))
{
try
{
ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");
scope.Connect();
ObjectQuery obquery = new ObjectQuery(query);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);
foreach (ManagementObject obj in searcher.Get())
{
try
{
resultList.Add("Name: " + obj["Name"].ToString());
resultList.Add("Port: " + obj["PortName"].ToString());
resultList.Add("DeviceID: " + obj["DeviceID"].ToString());
resultList.Add("DriverName: " + obj["DriverName"].ToString());
if (obj["Shared"].ToString().Equals(true.ToString()))
{
resultList.Add("Share Name: " + obj["ShareName"].ToString());
}
//resultList.Add("Status: " + obj["Status"].ToString());
//resultList.Add("Printer Status: " + obj["PrinterStatus"].ToString());
//resultList.Add("Printer State: " + obj["PrinterState"].ToString());
//int state = Int32.Parse(obj["ExtendedPrinterStatus"].ToString());
//switch (state)
//{
// case 1: //Other
// resultList.Add("Other");
// break;
// case 2: //Unknown
// resultList.Add("Unknown 2");
// break;
// case 7: //Offline
// resultList.Add("Offline");
// break;
// case 9: //error
// resultList.Add("Error");
// break;
// case 11: //Not Available
// break;
// default:
// resultList.Add("None of the above.");
// break;
//}
resultList.Add("");
}
catch
{
resultList.Add("Unknown");
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//resultList.Sort();
return resultList;
}
//Deletes the printer
public void WMIDeletePrinter(string pcname, string printerName)
{
try
{
if (PcNameIsNotNullOrVoid(pcname) && !string.IsNullOrEmpty(printerName))
{
string query = @"SELECT * FROM Win32_Printer WHERE Name = '" + printerName.Replace("\\", "\\\\") + "'";
pcname = CleanPCName(pcname);
ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");
scope.Connect();
SelectQuery obquery = new SelectQuery(query);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);
ManagementObjectCollection oObjectCollection = searcher.Get();
if (oObjectCollection.Count > 0)
{
foreach (ManagementObject oItem in oObjectCollection)
{
oItem.Delete();
MessageBox.Show(oItem["Name"].ToString() + " deleted.");
}
}
else
{
MessageBox.Show("Printer not Found");
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Thursday, October 15, 2015
List and Delete printers with WMI and .NET
Works, but looks like it was a work in progress I never completely finished.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment