How to get Network Printers in ASP.NET

5k views Asked by At

I need to show printers installed in network. I used the below code to show printers but locally it shows network printers, but when hosted in IIS it doesn't show network printer.(shows only local printers).

code -1:

     ApplicationPrinter printer = new ApplicationPrinter();
     ddlPrinters.DataSource = printer.InstalledPrinters();
     ddlPrinters.DataBind();
     ddlPrinters.SelectedItem.Text = printer.DefaultZebraPrinter();

code -2:

    ddlPrinters.Items.Clear();

        try
        {
            // Use the ObjectQuery to get the list of configured printers
            ObjectQuery oquery =
                new ObjectQuery("SELECT * FROM Win32_Printer");

            ManagementObjectSearcher mosearcher =
                new ManagementObjectSearcher(oquery);

            ManagementObjectCollection moc = mosearcher.Get();

            foreach (ManagementObject mo in moc)
            {
                PropertyDataCollection pdc = mo.Properties;
                foreach (PropertyData pd in pdc)
                {
                    if ((bool)mo["Network"])
                    {
                        ddlPrinters.Items.Add(mo["Name"].ToString());
                        break;
                    }

                }
            }
        }
        catch (ManagementException ex)
        {
            string msgDesc = string.Empty;
            string script = string.Empty;
            msgDesc = ex.Message;
            script = "<script language=\"javascript\">alert('" + msgDesc + "'); </script>";
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "UserMessage", script, false);
        }

Here if ((bool)mo["Network"]) is used to show only Network printers.

Is there any way to get network printers in ASP.NET?

2

There are 2 answers

0
David Nelson On

Adding this line to the section of the web.config does the trick. The userid provided needs to have the network printers mapped.

<identity impersonate="true" userName="domain\user" password="password" />
0
Yellowcake On

Have you tried installing the network printer on the workstation first, and then do a win32_printer query?

P.s. you can install it by \\printername