1

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?

abatishchev
  • 95,331
  • 80
  • 293
  • 426
shailesh
  • 11
  • 2

3 Answers3

2

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

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
1

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
}
Aseem Gautam
  • 18,765
  • 11
  • 83
  • 109
  • 1
    I'd recommend using the objectCategory=person instead of objectClass. ObjectCategory is single-valued and indexed, while objectClass is not --> using objectCategory makes your AD query faster – marc_s Jan 12 '10 at 10:13
  • @marc_s: One can use either both *objectCategory* and *objectClass* or *objectClass* only as using *objectCategory* only within the filter doesn't work in .NET. – Will Marcouiller Jul 13 '10 at 16:35
  • You should not use this method, as it also attempts to *read* values in Active Directory, rather than check authentication. You can have valid credentials but the code will fail because you don't have permission to look up users. – Ian Boyd Aug 18 '11 at 16:59
0

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

Scoregraphic
  • 6,972
  • 4
  • 40
  • 62