C# 如何从 Active Directory 获取用户的电子邮件地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/785527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a user's e-mail address from Active Directory?
提问by user95440
I am trying to get a user's email address in AD without success.
我试图在 AD 中获取用户的电子邮件地址但没有成功。
String account = userAccount.Replace(@"Domain\", "");
DirectoryEntry entry = new DirectoryEntry();
try {
DirectorySearcher search = new DirectorySearcher(entry);
search.PropertiesToLoad.Add("mail"); // e-mail addressead
SearchResult result = search.FindOne();
if (result != null) {
return result.Properties["mail"][0].ToString();
} else {
return "Unknown User";
}
} catch (Exception ex) {
return ex.Message;
}
Can anyone see the issue or point in the right direction?
任何人都可以看到问题或指出正确的方向吗?
采纳答案by Fredrik M?rk
Disclaimer:This code doesn't search for a single exact match, so for domain\j_doe
it may return domain\j_doe_from_external_department
's email address if such similarly named account also exists. If such behaviour is undesirable, then either use a samAccountNamefilter intead of an anrone used below or filter the resultsadditionally.
免责声明:此代码不会搜索单个完全匹配项,因此如果此类名称相似的帐户也存在,domain\j_doe
则它可能会返回domain\j_doe_from_external_department
的电子邮件地址。如果这种行为是不受欢迎的,那么要么使用samAccountName过滤器而不是下面使用的anr过滤器,要么另外过滤结果。
I have used this code successfully (where "account" is the user logon name without the domain (domain\account):
我已成功使用此代码(其中“帐户”是没有域(域\帐户)的用户登录名:
// get a DirectorySearcher object
DirectorySearcher search = new DirectorySearcher(entry);
// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + account + "))";
// specify which property values to return in the search
search.PropertiesToLoad.Add("givenName"); // first name
search.PropertiesToLoad.Add("sn"); // last name
search.PropertiesToLoad.Add("mail"); // smtp mail address
// perform the search
SearchResult result = search.FindOne();
回答by Jakob Christensen
You forgot a filter.
你忘记了过滤器。
Try adding this before calling FindOne:
在调用 FindOne 之前尝试添加:
search.Filter = String.Format("(sAMAccountName={0})", account);
回答by Nic Wise
update: fredrick nailed it....
更新:弗雷德里克钉了它....
Jakob is right. You need to filter your search. You can do all sorts of and
s and or
s there too if you need to, but I think sAMAccountName
is enough. You might want to fire up the ADSI tool (it's in the resource kit I think), which lets you walk AD like the registry. it's great for looking at properties. Then find a user, work out what prop you want (mail in this case) and what it's primary key
is - sAMAccountName
is a good one, but you may also want to filter on the node type.
雅各布是对的。您需要过滤您的搜索。如果需要,您也可以在那里执行各种and
s 和or
s,但我认为sAMAccountName
已经足够了。您可能想要启动 ADSI 工具(我认为它在资源工具包中),它可以让您像注册注册表一样处理 AD。非常适合查看属性。然后找到一个用户,找出你想要的道具(在这种情况下primary key
是邮件)以及它是什么-sAMAccountName
是一个很好的,但你可能还想过滤节点类型。
I'm on a mac, so I can't check it for you, but each node in AD has a type, and you can add that to your filter. I think it looks like this:
我使用的是 mac,所以我无为您检查,但是 AD 中的每个节点都有一个类型,您可以将其添加到您的过滤器中。我认为它看起来像这样:
((sAMAccountName=bob) & (type=User))
Again, check that - I know it's not type=user, but something LIKE that.
再次检查 - 我知道它不是 type=user,而是类似的东西。
回答by Oskar Duveborn
Also, where do you pull the username from (stored, user input, current identity)? A username can change (be renamed) easily - the SID/Windows Logon Identity on the other hand does not change - so you would be better off doing filters/searches by SID rather than samaccountname - if possible and/or needed design-wise...
另外,您从哪里提取用户名(存储的、用户输入的、当前身份)?用户名可以轻松更改(重命名)-另一方面,SID/Windows 登录标识不会更改-因此,如果可能和/或设计上需要,您最好按 SID 而不是 samaccountname 进行过滤/搜索。 ..
回答by SMerrill8
You guys are working too hard:
你们太辛苦了:
// Look up the current user's email address
string eMail = UserPrincipal.Current.EmailAddress;
回答by Kaarthikeyan
You can try the below GetUserEmail method. If You are looking out to find the email address for logged-in user in MVC then call the GetUserEmail()function with User.Identity.Name
您可以尝试下面的 GetUserEmail 方。如果您想在 MVC 中查找已登录用户的电子邮件地址,请使用User.Identity.Name调用GetUserEmail()函数
using System.DirectoryServices;
using System.Linq;
public string GetUserEmail(string UserId)
{
var searcher = new DirectorySearcher("LDAP://" + UserId.Split('\').First().ToLower())
{
Filter = "(&(ObjectClass=person)(sAMAccountName=" + UserId.Split('\').Last().ToLower() + "))"
};
var result = searcher.FindOne();
if (result == null)
return string.Empty;
return result.Properties["mail"][0].ToString();
}
GetUserEmail(User.Identity.Name) //Get Logged in user email address
回答by A. Lartey
You need to add references for System.DirectoryServices.AccountManagement and include this same references in your using statement. Now you will have access to the current users login details as listed below include the email address.
您需要为 System.DirectoryServices.AccountManagement 添加引用,并在 using 语句中包含相同的引用。现在您可以访问当前用户的登录详细信息,如下所列,包括电子邮件地址。
string loginname = Environment.UserName;
string firstname = UserPrincipal.Current.GivenName;
string lastname = UserPrincipal.Current.Surname;
string name = UserPrincipal.Current.Name;
string eMail = UserPrincipal.Current.EmailAddress;
回答by Muflix
What about this
那这个呢
public string GetEmailFromSamAccountName(string samAccountName, string domain="YOURCOMPANY")
{
using (var principalContext = new PrincipalContext(ContextType.Domain, domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, samAccountName);
return userPrincipal.EmailAddress;
}
}