Search code examples
c#windowsdriverwin32-process

Trouble when call AddPrinterDriver - winspool.drv


I'm trying to create a virtual printer using c# with some binding function from winspool.drv, I have successfully installed the printer into my windows 7 64bits, but win32 always causes the error code 216 whenever I try to install on a 32bits machine.

I decided to borrow my friends' computer, in which 10 computers with 32bit processor, there are only one can install the printer driver.

The error happend when I call AddPrinterDriver method. And here is my code:

[DllImport("winspool.drv", EntryPoint = "AddPrinterDriver", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool AddPrinterDriver(String pName, int Level, ref DRIVER_INFO_6 pDriverInfo);

Code to call it with

private bool InstallPrinterDriver(ref DRIVER_INFO_6 printerDriverInfo)
{
    bool printerDriverInstalled = false;
    printerDriverInstalled = NativeMethods.AddPrinterDriver(null, 6, ref printerDriverInfo);
    if (printerDriverInstalled == false)
    {
        //int lastWinError = Marshal.GetLastWin32Error();
        //throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not add printer Zody PDF printer driver.");
        logEventSource.TraceEvent(TraceEventType.Error,
                                      (int)TraceEventType.Error,
                                      "Could not add Zody PDF printer driver. " +
                                      String.Format(WIN32ERROR, Marshal.GetLastWin32Error().ToString()));
        Console.Write("\n" + String.Format(WIN32ERROR, Marshal.GetLastWin32Error().ToString()));
        Console.Write("\n"+printerDriverInfo);
    }
    return printerDriverInstalled;
}

The result is always failed with error code 216 even I had tried so many ways like change the pEnvironment = null or Windows NT x86. Then run with admin privileges and so on.

Update: the error 216's explanation: This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. -> that means I may running a 64bits program on a 32bits one. But, I'm pretty sure that the package has been built on a target of 32bit (x86) machine from Visual studio 2015.


Solution

  • The root cause of this is there are an existing library inside your computer, and you are trying to add a new one. There are 2 option either you ignore this error by coding and continue install the application normally, or you should delete everything in this directory:

    C:\Windows\System32\spool\drivers\W32X86\3