5

I need to verify users in the company using only their username - not their password.

So I need a method like this

public bool UserExists(string username)
{ ... }

I am aware of the System.DirectoryServices namespace but don't know where to start.

Any ideas?

There are 80,000+ records so try to bear that in mind.

Thank you.

Edit:

I have done it - my code is:

private bool UserExists(string userName, string domain)
{
    try
    {
        DirectoryEntry.Exists("WinNT://" + domain + ".[hidden].com/" + userName);
        return true;
    }
    catch (COMException)
    {
        return false;
    }
}

I don't know if it is correct, but it seems to work so far.

Michael's answer has two relevant parts:

Update #2:

I actually used this:

public static bool LoggedOnUserExists()
{
    var domain = new PrincipalContext(ContextType.Domain);

    UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName);

    return foundUser != null;
}
1
  • 2
    You should NOT use the WinNT provider anymore - it's strictly for backwards compatibility, but it typically doesn't work well in a AD network Commented Nov 29, 2010 at 15:47

1 Answer 1

6

In .NET 3.5 and up, you can use the System.DirectoryServices.AccountManagement namespaces to do this quite simply:

public bool UserExists(string username)
{
   // create your domain context
   using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
   {
       // find the user
       UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);

       return foundUser != null;
    }
}

This will work with the regular user name John Doe, or alternatively you can use the user's e-mail address ([email protected]), or his distinguished name (CN=John Doe) - see what the IdentityType enumeration has to offer :-)

Sign up to request clarification or add additional context in comments.

2 Comments

I assume this searches on the current domain? Is there anyway to use this method and specify a domain?
@Eddie: sure - the PrincipalContext has numerous overloaded constructors (perfectly documented on MSDN), which allow you to specify a domain and/or a container in that domain to use for searching

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.