0
votes

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".

1
has it printed by the time you come to display it?BugFinder
@BugFinder No but as soon as a job is sent to the queue.Aishwarya Shiva
Also its not a duplicate of the question @PatrickHofman mentioned. I know why NullReferenceException is thrown. But my question is why that function is throwing even there is data in the collection. Please remove Duplicate flag.Aishwarya Shiva
msdn.microsoft.com/en-us/library/… suggests you should refresh the queue before issuing the getprintjobinfocollectionBugFinder
@BugFinder Thanks a lot it worked. I hope someone will reopen this question and please add this as an answer. Because this might be helpful in future to someone else.Aishwarya Shiva

1 Answers

4
votes

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.