C# 使用C在active directory中查找与用户关联的所有电子邮件地址#
我正试图让c#返回与Active Directory中的用户关联的所有电子邮件地址。我们的许多用户都有多个电子邮件地址,我需要能够获得与单个用户关联的所有地址的列表。我使用下面的代码块,但它只返回一个电子邮件地址。任何帮助都将不胜感激C# 使用C在active directory中查找与用户关联的所有电子邮件地址#,c#,email,active-directory,C#,Email,Active Directory,我正试图让c#返回与Active Directory中的用户关联的所有电子邮件地址。我们的许多用户都有多个电子邮件地址,我需要能够获得与单个用户关联的所有地址的列表。我使用下面的代码块,但它只返回一个电子邮件地址。任何帮助都将不胜感激 string username = "user"; string domain = "domain"; List<string> emailAddresses = new List<string>(); PrincipalContext d
string username = "user";
string domain = "domain";
List<string> emailAddresses = new List<string>();
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username);
// Add the "mail" entry
emailAddresses.Add(user.EmailAddress);
foreach (String item in emailAddresses)
{
DropDownList1.Items.Add(item);
}
string username=“user”;
字符串domain=“domain”;
List emailAddresses=新列表();
PrincipalContext domainContext=新PrincipalContext(ContextType.Domain,Domain);
UserPrincipal user=UserPrincipal.FindByIdentity(域上下文,用户名);
//添加“邮件”条目
EmailAddress.Add(user.EmailAddress);
foreach(电子邮件地址中的字符串项)
{
DropDownList1.Items.Add(item);
}
您需要使用System.DirectoryServices命名空间在Active Directory中搜索您要查找的用户
一旦找到,您就可以获取附加到该特定用户的任何属性
有关如何在active directory中搜索,请参见以下链接
在active directory中,
mail
属性(UserPrincipal.EmailAddress
)只保存用户的主要电子邮件地址。要检索用户的所有地址,必须读取并分析msExchShadowProxyAddresses
属性,该属性包含所有地址,而不仅仅是SMTP地址(例如CIP)
像这样的方法应该会奏效:
static List<string> GetUserEmailAddresses(string username, string domain)
{
using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain))
using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username))
{
return ((DirectoryEntry)user.GetUnderlyingObject())
.Properties["msExchShadowProxyAddresses"]
.OfType<string>()
.Where(s => !string.IsNullOrWhiteSpace(s) && s.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
.ToList();
}
}
静态列表GetUserEmailAddresses(字符串用户名、字符串域)
{
使用(PrincipalContext domainContext=新PrincipalContext(ContextType.Domain,Domain))
使用(UserPrincipal user=UserPrincipal.FindByIdentity(域上下文,用户名))
{
return((DirectoryEntry)user.getUnderlinegObject())
.Properties[“msExchShadowProxyAddresses”]
第()类
.Where(s=>!string.IsNullOrWhiteSpace和&s.StartsWith(“smtp:,StringComparison.OrdinalIgnoreCase))
.ToList();
}
}
漂亮。谢谢你的帮助。这是一个改变。我将“msExchShadowProxyAddresses”
更改为仅“proxyaddresses”
以从正确的字段中提取。感谢您提供这些参考。我现在真的在复习它们!