Thursday, April 15, 2010

How to find out if a user exists on a domain or system?

So here I was, trying to grope through the System.DirectoryServices namesapce trying to find a way to check if a given username exists in the domain. What I wanted to do is this: If you have ever opened your computer management console, you would have noticed that when you attempt to add a user to a group, the dialogue would check if the username exists. I was trying to achieve the same functionality programmatically.

My application was required to do the following:

1. Present the users with an input box to type in a username to add and a drop down to select the group in which to add them
2. Check if the username is valid
2.1 If the username is valid, check if it already exists as a member of the group selected
2.1.1 If the username is valid AND it does not exist in the group selected, add to the group

I was able to (with help from support.microsoft.com KB article) figure out how to check if the user is member of a group but was having trouble trying to figure out how to check if the user actually exists in the domain(Active Directory) or system (WinNT)

I landed on the following article from Stackoverflow.com:

Faster way to find out if a user exists on a system? - Stack Overflow

I'm quoting the code snippet for quick reference:

using System.DirectoryServices.AccountManagement; //Add System.DirectoryServices.AccountManagement in Project Reference

public bool IsUserFound(String UserName)
{
bool UserExists;

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, UserName);
UserExists = (up != null);
}
return UserExists;
}
NOTE: ContextType enum contains three values: Machine (to check on local machine), Domain (To verify user on a domain) and ApplicationDirectory that represents AD LDS store.
If you are running this code from a machine which is not in the domain (or in a domain which does not have a trust relationship with user's domain) you would have to launch this thread as a security principal (that is a user) that has access to the target domain. The following MSDN link should get you started in doing that.

No comments:

Post a Comment