user162473
user162473

Reputation: 13

Searching specific folder, Active Directory

I am trying to access the names of all users in a specific folder, and i cannot find out how to do this. So far I can only search the entire active directory and limit my filter options but this is not enough. This is what I have so far:

DirectoryEntry dir = new DirectoryEntry("LDAP://path.local", "username", "password");
string filter = "(&(objectCategory=person)(objectClass=user);(!userAccountControl:1.2.840.113556.1.4.803:=2)(c=CA))";
string[] propertiesToLoad = new string[1] { "name" };
DirectorySearcher searcher = new DirectorySearcher(dir, filter, propertiesToLoad);
SearchResultCollection results = searcher.FindAll();
List<string> usernames   = new List<string>();
foreach (SearchResult result in results)
        {
            string name = (string)result.Properties["name"][0];
            if (name != null)
                usernames.Add(name);
        }

How would i go about searching for a specific file in the active directory, say if the path was Buisness\Canada\Users?

Upvotes: 1

Views: 3902

Answers (2)

JPBlanc
JPBlanc

Reputation: 72612

Ok, using Directories, you should not talk about folders, but OrganizationaUnit (OU).

So here is your vision :

enter image description here

And here (using ADSIEDIT.MSC) is the LDAP vision :

enter image description here

So the path to the MonOU folder is :

OU=MonOU,DC=SILOGIX-ESS01,DC=local

So the code to start your search begining this folder is :

DirectoryEntry dir = new DirectoryEntry("LDAP://path.local/OU=MonOU,DC=SILOGIX-ESS01,DC=local", "username", "password");
string filter = "(&(objectCategory=person)(objectClass=user);(!userAccountControl:1.2.840.113556.1.4.803:=2)(c=CA))";
string[] propertiesToLoad = new string[1] { "name" };
DirectorySearcher searcher = new DirectorySearcher(dir, filter, propertiesToLoad);
SearchResultCollection results = searcher.FindAll();
List<string> usernames   = new List<string>();
foreach (SearchResult result in results)
        {
            string name = (string)result.Properties["name"][0];
            if (name != null)
                usernames.Add(name);
        }

That's not all, you should also configure the scope of your search using :

searcher.SearchScope = SearchScope.Subtree;

Have a look to the 3 volues of SearchScope.

Last thing in a production context, you should write in your search the attributes you want to retreive (like in a SQL query) in order to be sure to retreive those you want and not to retreive too much (performance).

  searcher.PropertiesToLoad.Add("cn");
  searcher.PropertiesToLoad.Add("objectSid");

Upvotes: 4

Brian Desmond
Brian Desmond

Reputation: 4503

If your domain is called contoso.com and you want to search the path mentioned, you'd set this line like this:

DirectoryEntry dir = new DirectoryEntry("LDAP://OU=Users,OU=Canada,OU=Business,DC=contoso,DC=com", "username", "password");

Upvotes: 1

Related Questions