通过.NET的电子邮件地址搜索AD用户的正确方法
我在通过搜索其电子邮件地址来查找Active Directory中的用户的代码时遇到了一些问题。我尝试过2种方法,但我有时会发现FindOne()方法在某些场合不会返回任何结果。如果我在Outlook中查看GAL中的用户,我会看到列出的SMTP电子邮件地址。通过.NET的电子邮件地址搜索AD用户的正确方法
我的最终目标是确认用户是否存在于AD中。我只有电子邮件地址作为搜索条件,所以没有办法使用名字或姓氏。
方法1:使用邮件属性:
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(mail=" + email + ")";
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();
方法2:代理地址属性:
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(proxyAddresses=SMTP:" + email + ")"; // I've also tried with =smtp:
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();
我试图改变电子邮件地址输入的情况下,但它仍然没有返回结果。区分大小写是否存在问题?如果是这样,解决它的最好方法是什么?
我从来没有遇到任何用户电子邮件地址区分大小写搜索问题 - 如果您搜索的地址与ADSIEDIT中显示的完全相同,会发生什么情况?它是否在正确装箱时找到地址?
顺便说一句,我一直使用“邮件”属性,因为它返回用户的单个默认传出电子邮件地址,即使有多个地址附加到帐户。 “proxyAddresses”属性实际上是一个多值属性,您只需搜索以“smtp:”开头的值(属性中为小写)。但是,用户可能在他们的AD帐户上有多个SMTP地址(我们这样做),因此在这两者之间,“邮件”属性可能就是您要查找的内容。
如果您使用Exchange Server,proxyAddresses是获取其电子邮件地址的最可靠方法。主smtp地址由所有大写字母“SMTP:”表示,其他电子邮件地址将以小写字母“smtp:”作为前缀。 “邮件”属性不一定必须是主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("[email protected]");
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));
}
我发现,使用SysInternals ADExplorer是伟大的测试出/调试Active Directory查询。由于您可以构建查询并针对Active Directory运行它们,因此您可以查看结果以及轻松查看对象并查看其所有属性...
我想我已经找到了问题。 DirectoryEntry.Path被限定为特定的域。我更改了代码以使用全局编录并且搜索正在工作。我会尽快回复并更新。如果有人有任何要添加的东西,欢迎回答邮件与proxyAddresses。 – 2010-03-29 03:36:19