由于您使用的是 .NET 4,因此您应该查看System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有相关信息:
基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user - by e.g. his "samAccountName", or the Windows user name or something
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
string samAccountName = user.SamAccountName;
}
如果找不到用户名指定的用户,还可以使用新的搜索功能:
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) and a last name (Surname)
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = firstName;
qbeUser.Surname = lastName;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
新的 S.DS.AM 使得在 AD 中与用户和组一起玩变得非常容易!并且仅仅找到一个用户也应该相对较快。