yohan.jayarathna
yohan.jayarathna

Reputation: 3453

Connecting to Active Directory to retrieve user details using C#

I found an article about getting users from active directory from here

So possibly my code will like this

String strPath = "format of this path";
DirectoryEntry entry = null;
entry = new DirectoryEntry(strPath);

DirectorySearcher mySearcher = new DirectorySearcher(entry);

mySearcher.Filter = ("ObjectCategory=user");

foreach (SearchResult result in mySearcher.FindAll())
{
    String strName = result.GetDirectoryEntry().Name;
    //Do whatever
}

Can you please explain the strPath here ?? What is format of this ??

Note: I know my server information can get using my local ip "198.168.1.182" for testing purposes.

I am not sure the way I am thinking is correct.

Please Help !!!

Upvotes: 1

Views: 14894

Answers (2)

marc_s
marc_s

Reputation: 754240

Since you're on .NET 4, you should definitely check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

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 user by name
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "John Doe");

// if we found user - inspect its details
if(user != null)
{
    string firstName = user.GivenName;
    string lastName = user.Surname;
    string email = user.EmailAddress;
    string phone = user.VoiceTelephoneNumber;
}

The new S.DS.AM makes it really easy to play around with users and groups in AD:

Upvotes: 5

Iwan Luijks
Iwan Luijks

Reputation: 486

strPath is the LDAP URL, on which more information can be found here: http://en.wikipedia.org/wiki/LDAP#LDAP_URLs

The structure may look a bit strange at first but the example at wikipedia gives a nice summary of it.

Upvotes: 1

Related Questions