代码之家  ›  专栏  ›  技术社区  ›  ZorgoZ

机器环境下不区分大小写的SAM查找特定用户的性能方法

  •  0
  • ZorgoZ  · 技术社区  · 6 年前

    这段代码在 域上下文 :

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

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

    有人能提出一种既在机器环境中快速又不区分大小写的方法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   ZorgoZ    6 年前

    如果有许多本地用户,可能不是最佳解决方案,但它可以工作:

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