我试图获取所有用户在我们公司域中的电子邮件地址。 99%有效但有时我的输出中有y NullReferenceException。
代码:
string dom = "mydomain";
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dom); //domain, user, password
System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(entry);
ds.Filter = ("(objectClass=User)");
int count = 1;
foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
String email = de.Properties["mail"].Value.ToString();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
答案 0 :(得分:0)
行
中可能有NullReferenceException
String email = de.Properties["mail"].Value.ToString();
如果在Properties["mail"]
中返回null
值或其Value
属性为null
,则尝试调用ToString()
将导致异常。
这将有助于这种情况(C#6语法)
String email = de.Properties["mail"]?.Value?.ToString();
或
String email = null;
if (de.Properties["mail"] != null && de.Properties["mail"].Value != null)
{
email = de.Properties["mail"].Value.ToString();
}