shailesh
shailesh

Reputation: 11

Authentication against Active Directory using C#

I am just having a user name and not having any password. I just want to check if this user name exist in Active Directory. How do I go about it?

Upvotes: 1

Views: 1835

Answers (3)

marc_s
marc_s

Reputation: 754220

If you're on .NET 3.5, you can use the System.DirectoryServices.AccountManagement features. Your code would look something like:

// create a "principal context" - e.g. your domain (could be machine, too)
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

UserPrincipal user = UserPrincipal.FindByIdentity(pc, "username");

bool userExists = (user != null);

That should do the trick ;-)

For more details on S.DS.AM, see this excellent MSDN article:

Managing Directory Security Principals in the .NET Framework 3.5

Upvotes: 2

A G
A G

Reputation: 22559

Try this:

string strDomain = DOMAINNAME;
string strUserId = USERNAME;

string strPath = "LDAP://DC=" + strDomain.Trim() + ",DC=com";

DirectoryEntry de = new DirectoryEntry(strPath);
DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + strUserId.Trim() + "))";

SearchResult results = deSearch.FindOne();
if ((results == null))
{
    //No User Found
}
else
{
   //User Found
}

Upvotes: 1

Scoregraphic
Scoregraphic

Reputation: 7200

You can use the class DirectoryEntry for such tasks. See the Exists-method here: http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.exists.aspx

Upvotes: 0

Related Questions