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?
A:
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
2010-01-12 09:06:06
+1
A:
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
2010-01-12 09:40:21
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
2010-01-12 10:13:49
@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
2010-07-13 16:35:21
+1
A:
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
2010-01-12 10:13:05