2

I'm writing an application in C# that allows to clear default's printer queue.

In order to do so I have such piece of code :

String spoolDir = "C\\Windows\\System32\\spool\\PRINTERS";
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(spoolDir);
int spoolCount = dir.GetFiles().Length;
if (spoolCount > 0)
{
 using (PrintServer ps = new PrintServer())
 {
  System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();
  using (PrintQueue pq = new PrintQueue(ps, settings.PrinterName, PrintSystemDesiredAccess.AdministratePrinter))
  {
   pq.Purge();
  }
 }
} 

I have added to the assembly file :

[assembly: SecurityRules(SecurityRulesSet.Level1)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityTransparent()]

Unfortunatelly I get this error :

Attempt by security transparent method 'MS.Internal.PrintWin32Thunk.PrinterDefaults.Dispose(Boolean)' to access security critical method 'MS.Internal.PrintWin32Thunk.PrinterDefaults.InternalDispose(Boolean)' failed.

The application works perfectly on my PC (Win 7, 64 bit) where I'm developing the program, but throws exception as stated above while running it on target PC (Win XP, 32 bit).

Application uses 4.0 framework. I know that one workaround for such problems is downgrading framework to 3.5, but unfortunatelly I'm using a library that requires 4.0 framework.

When I change the PrintQueue constructor to :

PrintQueue pq = new PrintQueue(ps, settings.PrinterName)

Then I get access denied exception in Win XP.

What can I do to solve the problem ?

Thanks in advance for Your help :)

  • 1
    Well, you are fibbing. You said your code is doesn't make any security demands. But it does, PrintSystemDesiredAccess.AdministratePrinter is unsubtle. Kaboom when you don't run in full trust. – Hans Passant Jan 12 '15 at 23:34
  • 1
    Known issue: "SecurityCritical attribute is missing on MS.Internal.PrintWin32Thunk.PrinterDefaults.Dispose()." https://social.msdn.microsoft.com/Forums/windows/en-US/04d04890-0931-4ef0-aa79-02e9582bb806/attempt-by-security-transparent-method?forum=winforms – juFo May 12 '16 at 14:27
  • related: http://stackoverflow.com/questions/6635616/visual-studio-unit-test-security-exception – juFo May 12 '16 at 14:30

0 Answers0