views:

321

answers:

2

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?
}
A: 

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
how do you get the name of the printer? PrintQueue.Name is not the machine name as it is user settable
Simon
isn't this (@"\\PrinterServerName") the printer server name?
Mitch Wheat
that is the print server. but each printer on that server can have its own ipaddress
Simon
A: 

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