I am using vb.net and I want to check whether a particular user exists in Active Directory. If it does, I want to display the particular user's details. How to do it?
User login credentials are passed via textbox control
My code:
Dim de As DirectoryEntry = GetDirectoryEntry()
Dim ds As DirectorySearcher = New DirectorySearcher(de)
ds.Filter = "(&(objectClass=txt1.text))"
' Use the FindAll method to return objects to SearchResultCollection.
results = ds.FindAll()
Public Shared Function GetDirectoryEntry() As DirectoryEntry
Dim dirEntry As DirectoryEntry = New DirectoryEntry()
dirEntry.Path = "LDAP://ss.in:389/CN=Schema,CN=Configuration,DC=ss,DC=in"
dirEntry.Username = "ss.in\ssldap"
dirEntry.Password = "ss@123"
'Dim searcher As New DirectorySearcher
'searcher.SearchRoot = dirEntry
Return dirEntry
End Function
Where I pass the password. Is this code is correct? I am new to AD. Pls help me to do this?
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// your user exists - do something here....
}
else
{
// your user in question does *not* exist - do something else....
}
Or in VB.NET:
' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain)
' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, "SomeUserName")
If user IsNot Nothing Then
' your user exists - do something here....
Else
' your user in question does *not* exist - do something else....
End If
The new S.DS.AM makes it really easy to play around with users and groups in AD!