I have a method that I am using the get a list of departments in our active directory. However some (at least one that I know of) is not showing up. "EMP-Alumni Relations" is the one I am troubleshooting at the moment.
Here is the code I am using. If anyone can identify any potential problems I would appreciate it. I am at a loss for the moment. I have identified several users who are in the department so I know that should not be the issue.
ArrayList GetAdDepts ( )
{
DirectoryEntry myLdapConnection = SCDirectoryEntry.GetDirectoryEntry ( );
DirectorySearcher search = new DirectorySearcher ( myLdapConnection );
search.Filter = "(objectClass=user)";
search.PropertiesToLoad.Add ( "department" );
SearchResultCollection result = search.FindAll ( );
ArrayList departments = new ArrayList ( );
foreach ( SearchResult depart in result )
{
DirectoryEntry directoryEntry = depart.GetDirectoryEntry ( );
if ( directoryEntry.Properties.Contains ( "department" ) )
{
string dept = ( string ) depart.Properties [ "department" ] [ 0 ];
if ( dept.Trim ( ).StartsWith ( "EMP-" ) )
{
if ( !departments.Contains ( dept ) )
{
departments.Add ( dept );
}
}
}
}
return departments;
}
Are there more than 1000 users? If so you are probably hitting the limit described in the answer to this question.
Try setting:
search.PageSize = ... some non-zero value ...;
Also you should be disposing your disposable objects DirectorySearcher
, SearchResultCollection
, DirectoryEntry
, with a using statement e.g.:
using (var search = new DirectorySearcher(myLdapConnection ))
{
search.Filter = "(objectClass=user)";
search.PropertiesToLoad.Add ( "department" );
search.PageSize = 1000; // any non-zero value will work
using (var result = search.FindAll ( ))
{
...
foreach ( SearchResult depart in result )
{
using (var directoryEntry = depart.GetDirectoryEntry ( ))
{
...
}
}
}
}