【发布时间】:2008-11-27 19:26:39
【问题描述】:
如何在 Active Directory 中查找用户?
一些示例用户名是:
- avatopia\ian
- 头像\ian
- ian@avatopia.com
- ian@avatopia.local
- avatopia.com\ian
请务必注意,我不知道域名and i shouldn't be hard-coding it。
有些sample code on stack-overflow 失败了。
using System.DirectoryServices;
/// <summary>
/// Gets the email address, if defined, of a user from Active Directory.
/// </summary>
/// <param name="userid">The userid of the user in question. Make
/// sure the domain has been stripped first!</param>
/// <returns>A string containing the user's email address, or null
/// if one was not defined or found.</returns>
public static string GetEmail(string userid)
{
DirectorySearcher searcher;
SearchResult result;
string email;
// Check first if there is a slash in the userid
// If there is, domain has not been stripped
if (!userid.Contains("\\"))
{
searcher = new DirectorySearcher();
searcher.Filter = String.Format("(SAMAccountName={0})", userid);
searcher.PropertiesToLoad.Add("mail");
result = searcher.FindOne();
if (result != null)
{
email = result.Properties["mail"][0].ToString();
}
}
return email;
}
它专门确保您没有传递完整的用户名。例如
Bad: avatopia\ian
Bad: avatar\ian
Good: ian
Good: ian
因为不允许你通过域,所以无法区分两个用户
ian
ian
另一个人在 sackoverflow 上有 the same question,但接受的答案说你必须
首先找到命名上下文 所需的域
我 don't know 什么是“命名上下文”,我不知道什么是“必需域”。我真的不想写一个正则表达式来尝试将用户名解析为域名和帐户名,例如
domain.something\user-name
进入
domain.something
user-name
因为我知道在某些极端情况下我会出错。我想要在活动目录中查找用户的正确、预期的方法。
CodeProject How to do almost everything in Active Directory 上有一个不错的页面,但是您无法通过用户名查找用户信息
我希望我可以给我的域控制器 (whoever it is, where ever it is, whatever it's called) 一个用户名,它会确定该用户属于哪个域,与该域控制器对话,并完成工作。
【问题讨论】:
标签: .net active-directory