开发者

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 mySea开发者_如何学运维rcher = 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());
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜