Raymond Morphy
Raymond Morphy

Reputation: 2526

How to connect to an active directory server?

I'm using below code for connecting to an active directory server and retrieving its users.

But my web server is not in sub domain. Can I connect to it?

Or I should include its Ip address or something else?

DirectoryEntry entry = new DirectoryEntry("LDAP://dps.com", "Raymond", "xxxxxxx");

DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");

foreach (SearchResult result in mySearcher.FindAll())
{
   ResultPropertyCollection myResultPropColl = result.Properties;
   DataRow dr=reader.Tables[0].NewRow();
   dr[0]=myResultPropColl["samaccountname"][0].ToString()+"@"+Domain;
   reader.Tables[0].Rows.Add(dr);
   Response.Write(myResultPropColl["samaccountname"][0].ToString());
}

Upvotes: 2

Views: 5404

Answers (1)

marc_s
marc_s

Reputation: 754983

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:

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 - connects to the current default domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity("John Doe");

// find all users in your AD directory - set up a "query-by-example" 
// template to search for; here: a UserPrincipal, which is not locked out
UserPrincipal userTemplate = new UserPrincipal(ctx);
userTemplate.IsAccountLockedOut = false;

// create a PrincipalSearcher, based on that search template
PrincipalSearcher searcher = new PrincipalSearcher(userTemplate);

// enumerate all users that this searcher finds
foreach(Principal foundPrincipal in searcher.FindAll())
{
   UserPrincipal foundUser = (foundPrincipal as UserPrincipal);

   // do something with the userTemplate
}

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

If you cannot upgrade to S.DS.AM, what you need to do is make sure to use a proper LDAP string to connect to your server. That string should be something like:

 LDAP://servername/OU=Users,DC=YourCompany,DC=com

The servername is optional - you can also leave that out. But the LDAP string needs to be made up of at least one DC=xxxxx string, and possibly other LDAP segments.

Upvotes: 6

Related Questions