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

Performant way of finding specific user by case insensitive SAM in machine context

此代码在域上下文中非常有用:

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;
}

遗憾的是,此代码区分大小写。

谁能推荐一种在机器上下文中快速且不区分大小写的方法?

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

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;
    }
}