Is there a .NET way to enumerate all available network printers?
found this code here
private void btnGetPrinters_Click(object sender, EventArgs e)
{
// Use the ObjectQuery to get the list of configured printers
System.Management.ObjectQuery oquery =
new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");
System.Management.ManagementObjectSearcher mosearcher =
new System.Management.ManagementObjectSearcher(oquery);
System.Management.ManagementObjectCollection moc = mosearcher.Get();
foreach (ManagementObject mo in moc)
{
System.Management.PropertyDataCollection pdc = mo.Properties;
foreach (System.Management.PropertyData pd in pdc)
{
if ((bool)mo["Network"])
{
cmbPrinters.Items.Add(mo[pd.Name]);
}
}
}
}
Update:
"This API function can enumerate all network resources, including servers, workstations, printers, shares, remote directories etc."
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=741&lngWId=10
Fetch all printers available in the network - not just local printers
The WMI cannot enumerate network printers, only can list the shared printers registered in the local machine. To this task you can use the WNetEnumResource, WNetOpenEnum and WNetCloseEnum WinApi functions. Some time ago I wrote a sample of this using .Net
Try this article Enumerating All Network resources using Delphi Prism
, the code uses the Oxygene
language but can be translated to C# easily.
List available network printers (non-installed as well)
I do not believe there is anything in .NET that can do this, you will need to make a native call. Here is the MSDN page about how to enumerate network resources, what you will need to do is P/Invoke the WNetEnumResource
function to get NETRESOURCE
objects back.
You are looking for objects that have a dwType
of RESOURCETYPE_PRINT
, when you find them you check lpRemoteName
to get the name of the printer.
Here is a link to a example snippet implementing its use (Even though the URL states it is VB the code is in C#). I would post it here but the note on the page expressly does not allow copying and pasting of the script without permission of the author.
How to get the list of all printers in computer
Try this:
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
MessageBox.Show(printer);
}
How to get all network printers in asp.net 4.0
if you cannot find/reference the ManagementObjectSearcher Class probably is because you did not add the proper reference to: System.Management.dll to your C# project. Surely it is supported also by .NET 4.
as you can see in this question: ManagementObjectSearcher select network printers? you can find all network printers in this way:
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Printer");
var results = searcher.Get();
IList<ManagementBaseObject> printers = new List<ManagementBaseObject>();
foreach (var printer in results) {
if ((bool)printer["Network"]) {
printers.Add(printer);
}
}
List all network printers per user
Figured out a way. Here is the code for anyone that comes across this issue.
private void ddlBackupselectuser_SelectionChangeCommitted(object sender, EventArgs e)
{
lbBackupprinters.Items.Clear();
string selecteduser = ddlBackupselectuser.Text;
string computer = ddlBackupselectcomp.Text;
string sid;
lblBackuppwd.Visible = true;
txtBackuppwd.Visible = true;
cboBackuppwdshow.Visible = true;
//BEGIN GRAB PRINTERS FROM REGISTRY
try
{
NTAccount ntuser = new NTAccount(selecteduser);
SecurityIdentifier sID = (SecurityIdentifier)ntuser.Translate(typeof(SecurityIdentifier));
lblBackupStatus.Text = sID.ToString();
sid = sID.ToString();
}
catch (IdentityNotMappedException)
{
lblBackupStatus.Text = "ERROR "+ ddlBackupselectuser.Text.ToString() + " contains no profile information";
lbBackupprinters.Items.Add("No Printers Found");
return;
}
ConnectionOptions co = new ConnectionOptions();
co.EnablePrivileges = true;
co.Impersonation = ImpersonationLevel.Impersonate;
System.Net.IPHostEntry h = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
string IPAddress = h.AddressList.GetValue(0).ToString();
string lm = System.Net.Dns.GetHostName().ToString();
try
{
ManagementScope myScope = new ManagementScope("\\\\" + computer + "\\root\\default", co);
ManagementPath mypath = new ManagementPath("StdRegProv");
ManagementClass wmiRegistry = new ManagementClass(myScope, mypath, null);
const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
//ManagementClass wmiRegistry = new ManagementClass("root/default",
//"StdRegProv",null);
string keyPath = @"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider\\" + sid + "\\Printers\\Connections";
object[] methodArgs = new object[] { HKEY_LOCAL_MACHINE, keyPath, null };
uint returnValue = (uint)wmiRegistry.InvokeMethod("EnumKey", methodArgs);
if (null != methodArgs[2])
{
string[] subKeys = methodArgs[2] as String[];
if (subKeys == null)
{
lbBackupprinters.Items.Add("No Printers Found");
return;
}
ManagementBaseObject inParam = wmiRegistry.GetMethodParameters("GetStringValue");
inParam["hDefKey"] = HKEY_LOCAL_MACHINE;
string keyName = "";
foreach (string subKey in subKeys)
{
//Display application name
keyPath = @"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider\\" + sid + "\\Printers\\Connections" + subKey;
keyName = "DisplayName";
inParam["sSubKeyName"] = keyPath;
inParam["sValueName"] = keyName;
ManagementBaseObject outParam = wmiRegistry.InvokeMethod("GetStringValue", inParam, null);
lbBackupprinters.Items.Add(subKey);
}
}
else
{
lbBackupprinters.Items.Add("No Printers Found");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
Related Topics
Date Difference in Years Using C#
How to Make Texture2D Readable via Script
Serialize as Ndjson Using JSON.Net
Changing the View for a Viewmodel
Launch a Process Under Another User's Credentials
Executenonquery Doesn't Return Results
How to Get Actual Path from Uri Xamarin Android
64 Bit C# with a 32 Bit Vb6 Com Object
Winforms Application Hang Due to Systemevents.Onuserpreferencechanged Event
System.Drawing in Windows or ASP.NET Services
C# How to Loop User Input Until the Datatype of the Input Is Correct
Performance of Linq Any VS Firstordefault != Null
Keep Casing When Serializing Dictionaries