c# – 通过电子邮件地址从.NET搜索AD用户的正确方法

前端之家收集整理的这篇文章主要介绍了c# – 通过电子邮件地址从.NET搜索AD用户的正确方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些问题的代码,旨在通过搜索他们的电子邮件地址在Active Directory中查找用户.我已经尝试了2种方法,但有时我发现FindOne()方法在某些情况下不会返回任何结果.如果我在Outlook中查看GAL中的用户,请查看列出的SMTP电子邮件地址.

我的最终目标是确认该用户存在于AD中.我只有电子邮件地址作为搜索条件,所以没有办法使用名字或姓氏.

方法1:使用邮件属性

DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(mail=" + email + ")";
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();

方法2:proxyAddresses属性

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));
    }
原文链接:https://www.f2er.com/csharp/97669.html

猜你在找的C#相关文章