【问题标题】:How to get a PrinterName for a given ip address如何获取给定 IP 地址的 PrinterName
【发布时间】:2015-05-29 15:52:19
【问题描述】:
我正在使用PrintDocument 类进行打印。
我有一个要打印文档信息的数据库表。而不是拥有它的PrintName 我只有打印机的IP 地址。所有打印机都安装在本地。我正在开发一个可以打印这些文档的 Windows 服务。
在我的范围之外还有另一个应用程序,用户选择了一台打印机,但只有它的 IP 存储在 DB...所以
我怎样才能设置PrinterSettings.PrinterName只有它的IP地址??
【问题讨论】:
标签:
c#
printing
ip
printdocument
【解决方案1】:
打印机名称我假设您是指打印机在 Windows 中设置的名称,而不是打印机型号或共享名称。
我不太明白您所说的打印机安装在本地是什么意思。由于您有打印机的 IP 地址,您的计算机是充当打印机的打印服务器,还是从其他打印服务器安装和共享它们?
当您只有 IP 地址时,您实际上正在寻找的是打印机 TCPIPPrinterPort,它与打印机相关。不幸的是,C# 中的 PrintServer 类不返回关联端口的主机地址(这就是为什么我们总是将端口命名为“IP_10.200.49.230”等,因为这样您就可以找到端口按名称而不是主机地址,它包含在打印服务器类中。
在你的情况下,我会这样做:
static void Main(string[] args)
{
String serverName = "Print-Server"; //set servername (your own computername if you truly are hosting the printers locally)
String ipToSearchFor = "10.91.40.75";//ip to search for in this example
//this loads all TCPPrinterPorts into a Dictionary indexed by the ports Hostaddress (IP)
//I'm loading all because I assume you are going to iterate over them at some point, since It seems you have a list
Dictionary<string, ManagementObject> printerPorts = LoadScope(serverName, "select * from Win32_TCPIPPrinterPort");
//after we've got the ports, open the printserver
using (PrintServer ps = new PrintServer("\\\\" + serverName))
{
//find the queue where queueport.name equals name of port we look up from IP
var queue = ps.GetPrintQueues().Where(p => p.QueuePort.Name == printerPorts[ipToSearchFor]["Name"].ToString()).FirstOrDefault();
//print sharename
Console.WriteLine(queue.ShareName);
}
}
//Loads everything in scope into a dictionary, in this case indexed by hostaddress
private static Dictionary<string, ManagementObject> LoadScope(string server, string query)
{
ManagementScope scope = new ManagementScope("\\\\" + server + "\\root\\cimv2");
scope.Connect();
SelectQuery q = new SelectQuery(query);
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, q);
ManagementObjectCollection pp = search.Get();
Dictionary<string, ManagementObject> objects = new Dictionary<string, ManagementObject>();
foreach (ManagementObject p in pp)
{
string name = p["HostAddress"].ToString().ToLower();
if (!objects.ContainsKey(name))
objects.Add(name, p);
}
return objects;
}
我建议您遍历您的列表,然后从这里开始保存打印机的共享名和服务器名。