我有一些问题的代码,旨在通过搜索他们的电子邮件地址在Active Directory中查找用户.我已经尝试了2种方法,但有时我发现FindOne()方法在某些情况下不会返回任何结果.如果我在Outlook中查看GAL中的用户,请查看列出的SMTP电子邮件地址.
我的最终目标是确认该用户存在于AD中.我只有电子邮件地址作为搜索条件,所以没有办法使用名字或姓氏.
DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(mail=" + email + ")"; search.PropertiesToLoad.Add("mail"); SearchResult result = search.FindOne();
DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(proxyAddresses=SMTP:" + email + ")"; // I've also tried with =smtp: search.PropertiesToLoad.Add("mail"); SearchResult result = search.FindOne();
解决方法
如果您使用Exchange Server,则proxyAddresses是获取其电子邮件地址的最可靠手段.主smtp地址由所有大写“SMTP:”指示,其他电子邮件地址将以小写“smtp:”作为前缀.属性“mail”不一定必须是主SMTP地址,尽管通常是这样.
以下是我使用的一些代码的变体:
public static SearchResult FindAccountByEmail(string email) { string filter = string.Format("(proxyaddresses=SMTP:{0})",email); using (DirectoryEntry gc = new DirectoryEntry("GC:")) { foreach (DirectoryEntry z in gc.Children) { using (DirectoryEntry root = z) { using (DirectorySearcher searcher = new DirectorySearcher(root,filter,new string[] { "proxyAddresses","objectGuid","displayName","distinguishedName" })) { searcher.ReferralChasing = ReferralChasingOption.All; SearchResult result = searcher.FindOne(); return result; } } break; } } return null; } static void Main(string[] args) { SearchResult result = FindAccountByEmail("someone@somewhere.com"); string distinguishedName = result.Properties["distinguishedName"][0] as string; string name = result.Properties["displayName"] != null ? result.Properties["displayName"][0] as string : string.Empty; Guid adGuid = new Guid((byte[]) (result.Properties["objectGUID"][0])); string emailAddress; var emailAddresses = (from string z in result.Properties["proxyAddresses"] where z.StartsWith("SMTP") select z); emailAddress = emailAddresses.Count() > 0 ? emailAddresses.First().Remove(0,5) : string.Empty; Console.WriteLine(string.Format("{1}{0}\t{2}{0}\t{3}{0}\t{4}",Environment.NewLine,name,distinguishedName,adGuid,emailAddress)); }