2011-05-01 70 views
2

我使用下面的代码连接到活动目录服务器并检索其用户。如何连接到活动目录服务器?

但我的网络服务器不在子域。我可以连接到它吗?

或者我应该包括它的IP地址或其他东西?

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()); 
} 

回答

6

如果你在.NET 3.5及以上,你应该看看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读全部内容:

Managing Directory Security Principals in the .NET Framework 3.5

基本上,你可以定义域范围内,并可以轻松地查找用户和/或组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 
} 

新S.DS.AM使它非常容易与AD中的用户和群组玩转:

如果您无法升级到S.DS.AM,您需要做的是确保使用正确的LDAP字符串连接到您的服务器。该字符串应该是这样的:

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

servername是可选的 - 你也可以离开了这一点。但是,LDAP字符串需要由至少一个DC=xxxxx字符串以及可能的其他LDAP段组成。