我看到引用和提示,可以通过编程方式使用 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/