3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
vps
  • 1,337
  • 7
  • 23
  • 41

1 Answers1

5

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • is i include anynamespace in aspx.vb page – vps Oct 04 '12 at 08:24
  • where should i pass the domain arguments @marc_s – vps Oct 04 '12 at 08:31
  • 1
    @sudha.s: you can define where to search for your user in the various constructor overloads of `PrincipalContext` - [see the freely available MSDN docs for details](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalcontext.aspx) – marc_s Oct 04 '12 at 08:57
  • domain server path=LDAP://ss.in:389/CN=Schema,CN=Configuration,DC=ss,DC=in username=ssldap pwd=ss@123 – vps Oct 04 '12 at 09:25