The following is my code:
DirectorySearcher search = new DirectorySearcher( directory );
search.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(|(sn=*)))";
search.PropertiesToLoad.Add( "GivenName" );
search.PropertiesToLoad.Add( "OfficePhone" );
search.PropertiesToLoad.Add( "EmployeeNumber" );
SearchResultCollection results = search.FindAll();
int thisCount = results.Count;
string filePath = "C:\\test.csv";
string contents = string.Empty;
int counter = 0;
foreach( SearchResult result in results ) {
DirectoryEntry userEntry = result.GetDirectoryEntry();
string givenName = userEntry.Properties[ "userPrincipalName" ].Value.ToString();
string employeeNumber = userEntry.Properties[ "EmployeeNumber" ].Value.ToString();
string phoneNumber = userEntry.Properties[ "OfficePhone" ].Value.ToString();
counter = counter + 1;
}
System.IO.File.WriteAllText( filePath, contents );
The problem that I seem to not be able to get around is that when I start looping through the "results" object, the code blows up after givenName
has been assigned. The error I get is:
Object reference not set to an instance of an object.
I've tried to figure out how to assign this properly but I keep running into a wall with it. Any suggestions would be greatly appreciated. I'm pretty sure it has to do with me not understanding DirectorySearcher/DirectoryEntry correctly - but I could be wrong. :-)
Based on this statement:
the code blows up after givenName has been assigned...
this line of code:
userEntry.Properties[ "EmployeeNumber" ]
is blowing up and letting you know that there is no property named EmployeeNumber
or that the Value
of EmployeeNumber
is null
. I'm going to bet on the second and so change that line to this:
userEntry.Properties[ "EmployeeNumber" ] as string;
and your employeeNumber
field will be set to null
when it is null
but it won't throw an exception.