Search code examples
c#.netprintingconsole-applicationjobs

NullReferenceException thrown by GetPrintJobInfoCollection() when trying to get the print jobs from default printer


I am trying to display the print jobs currently in print queue of a default printer on the console using this code:

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;
    }
}

When there is no item in the print queue it succesfully displays "Queue Empty!".

But when I start document printing, NumberOfJobs=1 but GetPrintJobInfoCollection() throws NullReferenceException.

Why there is a job and still its returning null?

What can be the reason?

Also, I don't have a printer so I am trying to print it on "Microsoft Print to PDF".


Solution

  • If you look at the Microsoft link it shows that it refreshes the queue before asking for the GetPrintJobInfoCollection.

    While, it would seem logical that you only just grabbed the queue how out of date can it be, the fact their example specifically refreshes would suggest this is the way to go.