我正在尝试通过用户名“admin”搜索事件目录。我知道目录中有一个使用该用户名的用户,但搜索总是一无所获。
var attributeName = "userPrincipalName";
var searchString = "admin"
var ent = new DirectoryEntry("LDAP://"dc=corp,dc=contoso,dc=com")
var mySearcher = new DirectorySearcher(ent);
mySearcher.Filter = string.Format("(&(objectClass=user)({0}={1}))", attributeName, searchString);
var userResult = mySearcher.FindOne();
userResult 总是以 null 结尾。我很想知道为什么,一定是我遗漏了什么。
最佳答案
如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有相关信息:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "admin");
if(user != null)
{
// do something here....
}
使用此代码,您将通过以下属性搜索该用户:
DistinguishedName
:身份是一个专有名称 (DN)。Guid
:身份是一个全局唯一标识符 (GUID)。姓名
:身份是姓名。SamAccountName
:身份是安全帐户管理器 (SAM) 名称。Sid
:身份是安全描述符定义语言 (SDDL) 格式的安全标识符 (SID)。UserPrincipalName
:身份是用户主体名称 (UPN)。
新的 S.DS.AM 使得在 AD 中与用户和组一起玩真的很容易!
关于c# - 如何使用 C# 按用户名搜索 Active Directory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865154/