首页 > 解决方案 > 在机器上下文中通过不区分大小写的 SAM 查找特定用户的高效方法

问题描述

这段代码在域上下文中就像一个魅力:

var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);

它也适用于机器上下文,但速度极慢(在大约 20 个用户中找到一个用户需要 13 秒)。

但首先,这种方法不区分大小写,这对我来说是必须的。

我在某处找到了机器上下文的替代代码:

var context = new PrincipalContext(ContextType.Machine);
var user = new UserPrincipal(context)
{
    SamAccountName = username
};

using (var searcher = new PrincipalSearcher(user))
{
    user = searcher.FindOne() as UserPrincipal;
}

不幸的是,此代码区分大小写。

谁能建议一种在机器上下文中既快速又不区分大小写的方法?

标签: c#active-directorywindows-authentication

解决方案


如果有很多本地用户,可能不是最好的解决方案,但它有效:

var username = "wHaTeVer";
UserPrincipal user = null;

using (var context = new PrincipalContext(ContextType.Machine))
{
    user = new UserPrincipal(context);

    using (var searcher = new PrincipalSearcher(user))
    {
        user = searcher.FindAll().FirstOrDefault(x => x.SamAccountName.Equals(username, StringComparison.InvariantCultureIgnoreCase)) as UserPrincipal;
    }
}

推荐阅读