尝试从默认打印机获取打印作业时,GetPrintJobInfoCollection() 引发 NullReferenceException

Ais*_*iva 3 .net c# printing jobs console-application

我正在尝试使用以下代码在控制台上显示默认打印机的打印队列中当前的打印作业:

for (;;)
{
    string printerName = new System.Drawing.Printing.PrinterSettings().PrinterName;
    System.Printing.LocalPrintServer localPrintServer = new System.Printing.LocalPrintServer();
    System.Printing.PrintQueueCollection printQueues = localPrintServer.GetPrintQueues(new[] { System.Printing.EnumeratedPrintQueueTypes.Local, System.Printing.EnumeratedPrintQueueTypes.Connections });

    if (printQueues == null) return;

    System.Printing.PrintQueue queue = printQueues.Where(x => x.Name.Equals(printerName)).FirstOrDefault();
    if (queue.NumberOfJobs <= 0)
        Console.WriteLine("Queue Empty!");
    else
    {
        Console.WriteLine("Number of Jobs: " + queue.NumberOfJobs);
        foreach (System.Printing.PrintSystemJobInfo psji in queue.GetPrintJobInfoCollection())
        {
            Console.WriteLine(psji.Name);
        }
        Console.WriteLine("\n\nPress any key to exit...");
        Console.ReadLine();
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

当打印队列中没有项目时,它会成功显示“队列为空!”。

但是当我开始文档打印时,NumberOfJobs=1 但GetPrintJobInfoCollection()抛出NullReferenceException.

为什么有工作却又回来了null

可能是什么原因?

另外,我没有打印机,所以我尝试在“Microsoft Print to PDF”上打印它。

Bug*_*der 6

如果您查看Microsoft 链接,它会显示它在请求 GetPrintJobInfoCollection 之前刷新队列。

虽然,您只抓取队列似乎是合乎逻辑的,它有多过时,但他们的示例专门刷新的事实表明这就是要走的路。