2014-09-01 44 views
1

我试过这个C#代码来将打印机和打印机驱动程序添加到Windows。它在Windows 7上工作,但不在Windows 8上。代码调用moPrinter.Put()时发生异常(通用故障)。任何人都可以说出为什么在运行Windows 8时遇到此错误,为什么不是Windows 7?安装打印机驱动程序的代码适用于Windows 7,但不适用于Windows 8

public static bool AddCanonPrinter() 
    { 
     bool flag = true; 
     try 
     { 
      String portNumber = "9100"; 
      String printerIP = "157.198.192.42"; 
      String portName = "IP_" + printerIP; 
      ConnectionOptions options = new ConnectionOptions(); 
      options.EnablePrivileges = true; 
      ManagementScope mscope = new ManagementScope(ManagementPath.DefaultPath, options); 
      mscope.Connect(); 

      ManagementPath mpPort = new ManagementPath("Win32_TCPIPPrinterPort"); 
      ManagementClass mcPort = new ManagementClass(mscope, mpPort, new ObjectGetOptions()); 
      ManagementObject moPort = mcPort.CreateInstance(); 
      moPort.Properties["Name"].Value = portName; 
      moPort.Properties["HostAddress"].Value = printerIP; 
      moPort.Properties["PortNumber"].Value = portNumber; 
      moPort.Properties["Protocol"].Value = 1; 
      moPort.Put(); 

      ManagementPath mpPrinter = new System.Management.ManagementPath("Win32_Printer"); 
      ManagementClass mcPrinter = new ManagementClass(mscope, mpPrinter, new ObjectGetOptions()); 
      ManagementObject moPrinter = mcPrinter.CreateInstance(); 
      moPrinter.Properties["Name"].Value = "Canon"; 
      moPrinter.Properties["DeviceID"].Value = "Canon"; 
      moPrinter.Properties["DriverName"].Value = "Canon iR C2880/C3380"; 
      moPrinter.Properties["PortName"].Value = portName; 
      moPrinter.Properties["Network"].Value = true; 
      moPrinter.Properties["Shared"].Value = false; 
      moPrinter.Put(); 
     } 
     catch 
     { 
      int msgCode = Marshal.GetLastWin32Error(); 
      string msg = GetSystemMessage(msgCode); 
      flag = false; 

     } 

     return flag; 
    } 

回答

0

其实在我调查的问题,我发现,打印机驱动程序的名字都在这样情况下可以使用相同的代码,Windows 8的不同,在Windows 8

+0

成功的作品是有办法通过代码或文件系统的任何位置检索可用的打印机驱动程序名称 – Gomiunik 2014-12-11 16:45:17

+0

是的。打印机驱动程序的列表存储在注册表中的SYSTEM \ CurrentControlSet \ Control \ Print \ Environments \ Windows x64 \ Drivers \ Version-3中。 (用windows x86 for 32bit驱动程序替换windows x64) – 2015-02-03 07:53:23

相关问题