如何获取给定IP地址的PrinterName

时间:2015-05-26 19:44:05

标签: c# printing ip printdocument

我正在使用PrintDocument课程进行打印。

我有一个数据库表,其中包含要打印的文档信息。而不是拥有PrintName我只有打印机的IP地址。所有打印机都在本地安装。我正在开发一个可以打印这些文档的Windows服务。

我的范围之外还有另一个应用程序,用户选择了一台打印机,但只是其IP存储在DB ...所以

如何设置PrinterSettings.PrinterName只拥有其IP地址?

1 个答案:

答案 0 :(得分:1)

通过printername我假设您的意思是打印机在Windows中设置的名称,而不是打印机型号或共享名称。 我真的不明白你在本地安装打印机的意思。您的计算机是否充当打印机的打印服务器,因为您拥有其IP地址,或者是否已从其他打印服务器安装和共享?

当您只拥有IP地址时,您实际需要的是打印机TCPIPPrinterPort,然后与打印机相关。不幸的是,C#中的PrintServer类没有返回相关端口的主机地址(这就是为什么我们始终命名我们的端口“IP_10.200.49.230”之类的,因为那时你可以找到端口按名称而不是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。