ZorgoZ
ZorgoZ

Reputation: 3567

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

This code works like a charm in domain context:

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

It also works in machine context, but it is extremely slow (finding a user among around twenty takes 13s).

But first of all, this method is case insensitive, which is a must for me.

I have found somewhere an alternate code for machine context:

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

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

Unfortunately, this code is case sensitive.

Can anyone suggest an approach that is both quick in machine context and case insensitive?

Upvotes: 1

Views: 799

Answers (1)

ZorgoZ
ZorgoZ

Reputation: 3567

Might not be the best solution if there are many local users, but it works:

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

Upvotes: 3

Related Questions