I’m querying our Active Directory with the following code:
using (DirectorySearcher search = new DirectorySearcher(de))
{
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("employeeid");
search.PropertiesToLoad.Add("employeenumber");
search.PropertiesToLoad.Add("distinguishedname");
search.PropertiesToLoad.Add("mail");
search.Filter = @"(&(objectClass=user)(employeeid=*)(employeenumber=*))";
search.PageSize = 3000;
SearchResultCollection src = search.FindAll();
foreach (SearchResult rec in src)
{
yield return new ADUser()
{
Name = rec.Properties["cn"][0].ToString(),
Path = rec.Properties["distinguishedname"][0].ToString(),
Acctno = rec.Properties["employeeid"][0].ToString(),
Personno = rec.Properties["employeenumber"][0].ToString(),
Email = rec.Properties["mail"][0].ToString()
};
}
}
As you can see, I’m trying to convert the results into an IEnumerable list of ADUser (my own class defined like this):
public class ADUser
{
public string Name { get; set; }
public string Path { get; set; }
public string Acctno { get; set; }
public string Personno { get; set; }
public string Email { get; set; }
}
However, my code crashes anytime I hit a user who does not have an email entry. It seems as though the SearchResult does not contain a property for mail when the user has no email. Is there a way to get the result to return the property with a null or empty value instead?
Thanks for your help.
Edit after comment: