c# - 使用 ManagementClass 将打印机添加到本地计算机

标签 c# printing

我看到引用和提示,可以通过编程方式使用 ManagementClass 等将网络打印机添加到本地计算机。但是我还没有找到任何关于这样做的实际教程。

有没有人实际使用 ManagementClass 来做到这一点?

我这样做:

var connectionOption = new ConnectionOption();
var mgmScope = new ManagementScope("root\cimv2",connectionOptions);

var printerClass = new ManagementClass(mgmScope, new ManagementPath("Win32_Printer"),null);
var printerObj = printerClass.CreateInstance();

printerObj["DeviceID"] = prnName;     //
printerObj["DriverName"] = drvName;   // full path to driver
printerObj["PortName"] = "myTestPort:";

var options = new PutOptions {Type = PutType.UpdateOrCreate};
printerObj.Put(options);   

所有这一切都会产生一个错误“Generic Failure”

我无法弄清楚我错过了什么.....任何对此的帮助或想法将不胜感激。

我认为我需要更好地解释我正在尝试做的事情...当所需的打印机未绑定(bind)到打印服务器时,我需要: 创建一个 tcpip 原始端口, 通过 tcp/ip 连接打印机, 安装驱动程序, 可选择设置默认值。

我希望 WMI 基本上可以解决所有这些问题,但事实并非如此。

谢谢!

最佳答案

WMI Win32_Printer 类提供了一个名为 AddPrinterConnection 的方法来 将网络打印机添加到本地打印机列表。下面的代码 展示了如何使用 Win32_Printer 类连接网络打印机。

请注意,在某些情况下 AddPrinterConnection 会失败 连接远程打印机。在下面的示例中,我列出了最多 常见错误案例。

using (ManagementClass win32Printer = new ManagementClass("Win32_Printer"))
{
  using (ManagementBaseObject inputParam =
     win32Printer.GetMethodParameters("AddPrinterConnection"))
  {
    // Replace <server_name> and <printer_name> with the actual server and
    // printer names.
    inputParam.SetPropertyValue("Name", "\\\\<server_name>\\<printer_name>");

    using (ManagementBaseObject result = 
        (ManagementBaseObject)win32Printer.InvokeMethod("AddPrinterConnection", inputParam, null))
    {
      uint errorCode = (uint)result.Properties["returnValue"].Value;

      switch (errorCode)
      {
        case 0:
          Console.Out.WriteLine("Successfully connected printer.");
          break;
        case 5:
          Console.Out.WriteLine("Access Denied.");
          break;
        case 123:
          Console.Out.WriteLine("The filename, directory name, or volume label syntax is incorrect.");
          break;
        case 1801:
          Console.Out.WriteLine("Invalid Printer Name.");
          break;
        case 1930:
          Console.Out.WriteLine("Incompatible Printer Driver.");
          break;
        case 3019:
          Console.Out.WriteLine("The specified printer driver was not found on the system and needs to be downloaded.");
          break;
      }
    }
  }
}

关于c# - 使用 ManagementClass 将打印机添加到本地计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16040148/

相关文章:

api - 如何将安卓设备连接到打印机?

r - 打印数据框,列居中对齐

c++ - 什么相当于C/C++中C#的PrintDocument?

c# - "Active"控制和 "Focused"控制之间的区别

c# - .NET Entity Framework - 使用 .Contains() 在 Where 表达式中查找字节值

c# - 从对列表创建邻接列表类型结构

c# - 加快 SQL Server 2008 中 185k 行的更新?

c# - 如何从 web.config 添加和访问连接字符串

excel - 用户选择的打印范围

python - 将要打印的图像发送到默认打印机...python