C# 机器上下文中不区分大小写的SAM查找特定用户的有效方法

C# 机器上下文中不区分大小写的SAM查找特定用户的有效方法,c#,active-directory,windows-authentication,C#,Active Directory,Windows Authentication,此代码在域上下文中就像一个符咒一样工作: var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); var context = new PrincipalContext(ContextType.Machine); var user = new UserPrincipal(context) { SamAccountName = username }; using (v

此代码在域上下文中就像一个符咒一样工作

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

using (var searcher = new PrincipalSearcher(user))
{
    user = searcher.FindOne() as UserPrincipal;
}
它也可以在机器环境下工作,但速度非常慢(在大约20个用户中找到一个用户需要13秒)

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

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

var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
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;
    }
}