我使用以下代码查询Active Directory:
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()
};
}
}
正如您所看到的,我试图将结果转换为ADUser的IEnumerable列表(我自己的类定义如下):
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; }
}
但是,当我遇到没有电子邮件条目的用户时,我的代码会崩溃。当用户没有电子邮件时,似乎SearchResult不包含邮件属性。有没有办法让结果返回属性为null或空值?
感谢您的帮助。
答案 0 :(得分:1)
评论后编辑:
if (rec.Properties.Contains("mail") && rec.Properties["mail"] != null)
{
Email = rec.Properties["mail"][0].ToString()
}
else
{
Email = "No mail"; # or Email = ""; if you want no text returned
}
答案 1 :(得分:-1)
你应该可以使用??使用电子邮件字符串“null coalescing”运算符。
string s1 = null; string s2 = s1 ?? "S1 was null." // Prints: s2 == "S1 was null."