使用新的.net打印API(System.Printing.dll)如何获取网络打印机的IPAddress?

时间:2009-11-09 05:35:03

标签: .net .net-3.5 printing

使用新的.net打印API(System.Printing.dll)如何获取网络打印机的IPAddress?

我正在看的课程是

以下是一些示例代码

PrintServer printServer = new PrintServer(@"\\PrinterServerName");
foreach (PrintQueue queue in printServer.GetPrintQueues())
{
   Debug.WriteLine(queue.Name);
   Debug.WriteLine(queue.QueuePort.Name);
   //how do i get the ipaddress of the printer attached to the queue?
} 

2 个答案:

答案 0 :(得分:0)

您可以使用打印机的计算机名称获取IPAddress:

IPHostEntry hostInfo = Dns.GetHostByName("MachineName");    
string IPAddress = hostInfo.AddressList[0].ToString();

答案 1 :(得分:0)

到目前为止,我有这个。我不得不求助于ManagementObjectSearcher来获取端口的ipaddress。

我现在接受这个答案。如果有人知道在没有ManagementObjectSearcher的情况下这样做,我会接受这个答案。

public virtual IEnumerable<Printer> GetPrinters()
{
    var ports = new Dictionary<string, IPAddress>();
    var selectQuery = new SelectQuery("Win32_TCPIPPrinterPort");
    selectQuery.SelectedProperties.Add("CreationClassName");
    selectQuery.SelectedProperties.Add("Name");
    selectQuery.SelectedProperties.Add("HostAddress");
    selectQuery.Condition = "CreationClassName = 'Win32_TCPIPPrinterPort'";

    using (var searcher = new ManagementObjectSearcher(Scope, selectQuery))
    {
        var objectCollection = searcher.Get();
        foreach (ManagementObject managementObjectCollection in objectCollection)
        {
            var portAddress = IPAddress.Parse(managementObjectCollection.GetProperty<string>("HostAddress"));
            ports.Add(managementObjectCollection.GetProperty<string>("Name"), portAddress);
        }
    }


    using (var printServer = new PrintServer(string.Format(@"\\{0}", PrinterServerName)))
    {
        foreach (var queue in printServer.GetPrintQueues())
        {
            if (!queue.IsShared)
            {
                continue;
            }
            yield return new Printer
                         {
                            Location = queue.Location,
                            Name = queue.Name,
                            PortName = queue.QueuePort.Name,
                            PortAddress = ports[queue.QueuePort.Name]
                         };
        }
    }
}