如何获得一个给定的ip地址的prinintername

本文关键字:ip 地址 prinintername 一个 何获得 | 更新日期: 2023-09-27 17:50:46

我使用PrintDocument类打印。

我有一个DB表有文档信息要打印。而不是它的PrintName,我只有打印机的IP地址。所有打印机都安装在本地。我正在开发一个可以打印这些文件的windows服务。

还有另一个应用程序,超出了我的范围,用户选择了一个打印机,但只是它的IP存储在DB…所以

我如何设置PrinterSettings.PrinterName只有它的IP地址??

如何获得一个给定的ip地址的prinintername

我假设您指的是在Windows中设置打印机的名称,而不是打印机型号或sharename。我不太明白你说的打印机安装在本地是什么意思。您的计算机是否作为打印机的打印机服务器(因为您有它们的IP地址),或者它们是从另一个打印机服务器安装和共享的?

当您只有IP地址时,您实际寻找的是打印机TCPIPPrinterPort,它随后与打印机相关。不幸的是,c#中的PrintServer类不返回关联端口的主机地址(这就是为什么我们总是将端口命名为"IP_10.200.49.230"或类似的原因,因为这样你可以通过名称而不是hostaddress找到端口,hostaddress包含在PrintServer类中。

在你的情况下,我会这样做:

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;
}

我建议你遍历你的列表,从这里开始,也保存打印机的sharename和servername