0

Using the new .net printing API (System.Printing.dll) how do you get the IPAddress of a network printer?

The classes i am looking at are

Here is some example code

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?
} 
Simon
  • 33,714
  • 21
  • 133
  • 202

2 Answers2

0

You can get the IPAddress by using the machine name of the Printer:

IPHostEntry hostInfo = Dns.GetHostByName("MachineName");    
string IPAddress = hostInfo.AddressList[0].ToString();
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

So far i have this. I have had to resort to ManagementObjectSearcher to get the ipaddress of the port.

I will accept this answer for now. If anyone knows a way of doing this without ManagementObjectSearcher I will accept that answer instead.

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]
                         };
        }
    }
}
Simon
  • 33,714
  • 21
  • 133
  • 202
  • So is it possible to print to a network printer from ASP.NET? Please see my question at http://stackoverflow.com/questions/3729153/printing-from-asp-net-to-a-network-printer – Prabhu Sep 16 '10 at 19:43