打印机状态返回错误值

时间:2013-04-11 06:11:19

标签: c# network-printers

我正在尝试获取网络打印机的状态。我尝试了WMI代码link。但即使我删除了网络电缆,它总是会转到其他部分。

这是我尝试过的代码:

ManagementObjectSearcher searcher = new 
             ManagementObjectSearcher("SELECT * FROM Win32_Printer");

string printerName = "";

foreach (ManagementObject printer in searcher.Get())
{
    printerName = printer["Name"].ToString().ToLower();

    if (printer["WorkOffline"].ToString().ToLower().Equals("true") && printer["Default"].ToString().ToLower().Equals("true"))

    {
       string s = "Printer  offline" + printerName;
       listBox1.Items.Add(s);
    }
    else
    {
        // printer is not offline
        //   Console.WriteLine("Your Plug-N-Play printer is connected.");

        string s = "Printer found and is online " + printerName;
        listBox1.Items.Add(s);
    }

2 个答案:

答案 0 :(得分:1)

查看条件

printer["PrinterState"].ToString().ToLower().Equals("Offline")
// this would mean offline == Offline which would be false

你需要小写的比较,你有一个错字离线有一个大写锁定 O

答案 1 :(得分:1)

比较可能不正确......导致声明

ConsoleWriteLine(printer["PrinterState"].ToString());

返回" 0"当打印机在线时," 128"当此故障由于任何原因(断电,卸载,电缆连接,网络故障等)

正确的比较必须是:

离线

printer["PrinterState"].ToString().ToLower().Equals("128")

printer["PrinterState"].ToString().ToLower().Equals("0")在线