Attempting to find printers / shares in Active Directory using C#.
This is my sample code that works for users however I cannot seen to be able to find a printer using the same concept. (I am new to Active Directory).
DirectoryEntry entry = new DirectoryEntry();
entry.Path = "LDAP://xxx.xxx.xx.xx/CN=Printers;DC=domainName, DC=com";
entry.Username = @"domainName.com\Administrator";
entry.Password = "admin";
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
Any assistance would be greatly appreciated.
In contrast to users (CN=Users) there is no CN=Printers container in Active Directory after installation.
Printers are published in Active Directory in the releated computer container. What does releated computer container mean? Well, open Active Directory Users and Computers MMC snap-in and follow this procedure:
So, you see printers are published in Active Directory in the releated computer container (the printer belongs to) and not in one common container such as CN=Printers.
So, to search for a printer object in Active Directory, you have to specify a different LDAP path. For example you could specify the root of your Active Directory as the search root:
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Path = "LDAP://xxx.xxx.xxx.xxx/DC=domainName,DC=com";
entry.Username = @"domainName.com\Administrator";
entry.Password = "SecurePassword";
using (DirectorySearcher search = new DirectorySearcher(entry))
{
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
}
}
Of course, you could also specify as search root the LDAP path to the computer where your printer
is shared on. For example if your printer is shared on a computer called server10 and this computer is located in the CN=Computers container, then specify this LDAP path:
LDAP://xxx.xxx.xxx.xxx/CN=server10,CN=Computers,DC=domainName,DC=com
If you share a printer on the domain controller then the LDAP path is slightly different (because by default domain controller computer objects are located in the OU=Domain Controllers organizational unit):
LDAP://xxx.xxx.xxx.xxx/CN=DomainControllerName,OU=Domain Controllers,DC=domainName,DC=com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With