Reputation: 617
i want to get list of OU from Active Directory.
i have only domain name.
how can i achieve this using c#?
Upvotes: 5
Views: 14715
Reputation: 678
Add a reference to System.DirectoryServices in the project
public static List<string> ListOu()
{
List<string> ous = new List<string>();
using (DirectoryEntry root = new DirectoryEntry("LDAP://dc=DOMAIN,dc=COM"))
{
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.Filter = "(&(objectClass=organizationalUnit))";
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("distinguishedName");
var result = searcher.FindAll();
foreach (SearchResult entry in result)
{
ous.Add(entry.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());
}
result.Dispose();
searcher.Dispose();
}
return ous;
}
Upvotes: 4
Reputation: 755321
Try something like this:
// connect to "RootDSE" to find default naming context
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();
// bind to default naming context - if you *know* where you want to bind to -
// you can just use that information right away
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);
// set up directory searcher based on default naming context entry
DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);
// SearchScope: OneLevel = only immediate subordinates (top-level OUs);
// subtree = all OU's in the whole domain (can take **LONG** time!)
ouSearcher.SearchScope = SearchScope.OneLevel;
// ouSearcher.SearchScope = SearchScope.Subtree;
// define properties to load - here I just get the "OU" attribute, the name of the OU
ouSearcher.PropertiesToLoad.Add("ou");
// define filter - only select organizational units
ouSearcher.Filter = "(objectCategory=organizationalUnit)";
// do search and iterate over results
foreach (SearchResult deResult in ouSearcher.FindAll())
{
string ouName = deResult.Properties["ou"][0].ToString();
}
If you have a domain name (e.g. mycompany.com
), then the LDAP root domain typically will be called dc=mycompany,dc=com
- that's a convention, it doesn't have to be that way though. That's why I'm connecting to the LDAP://RootDSE
virtual LDAP root and I read out the property Default Naming Context
which gives me the default LDAP path.
If you know where you want to connect to - feel free to skip that first step and just provide the valid LDAP path (e.g. LDAP://dc=YourCompany,dc=co,dc=jp
or whatever) to create the domainRoot
directory entry.
Upvotes: 7