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.

Advertisements
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

  • Comic for July 25, 2017
    Dilbert readers - Please visit Dilbert.com to read this feature. Due to changes with our feeds, we are now making this RSS feed a link to Dilbert.com.
%d bloggers like this: