I concur with comment by
CzBonfire, 4-Jun-15 8:09am.
His code also worked for me!
Seems strange to declare a "
new PrintQueue(ps, ...)", but if I try to simply do "ps.GetPrintQueue(strPrintQueueName)", I get a valid PrintQueue object, but when trying to do the "pq.Purge()" it fails with an access violation.
My code (in C#) is below. I have a couple application settings that are referenced (PrinterQueueName and QueueClearTimeout_sec).
I found that if you want to confirm that the jobs have been cleared, you need to call pq.Refresh() to update the NumberOfJobs property. I built in a timeout to wait for the jobs to be cleared.... not sure if this is necessary or not. After the timeout, if NumberOfJobs is still>0, it would be possible to inform user that it failed to clear the queue (not implemented in my code here).
static void Main(string[] args)
{
using (LocalPrintServer ps = new LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer))
{
Console.WriteLine(String.Format("Print Server name: {0}", ps.Name));
using (PrintQueue pq = new PrintQueue(ps, Settings.Default.PrinterQueueName, PrintSystemDesiredAccess.AdministratePrinter))
{
Console.WriteLine(String.Format("Print Queue name: {0}", pq.Name));
Console.WriteLine(String.Format(" Number of jobs: {0}", pq.NumberOfJobs));
if (pq.NumberOfJobs > 0)
{
pq.Purge();
pq.Refresh();
DateTime datTimeout = DateTime.Now.AddSeconds(Settings.Default.QueueClearTimeout_sec);
while ((pq.NumberOfJobs > 0) && (DateTime.Now < datTimeout))
{
Thread.Sleep(500);
pq.Refresh();
}
Console.WriteLine(String.Format(" After Purge(), number of jobs: {0}", pq.NumberOfJobs));
}
}
}
}