来自Active Directory的用户信息

时间:2013-09-09 13:51:52

标签: active-directory c#-2.0 webpage asp.net-3.5

我正在使用用户ID(用户名)从AD获取他/她的信息。我想知道是否可以使用其他标准,例如姓氏,电子邮件地址等来做同样的事情。

这是我用户现在过滤掉用户的内容:

        string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();
        DirectoryEntry de = new DirectoryEntry(adPath);
        DirectorySearcher deSearch = new DirectorySearcher();
        deSearch.SearchRoot = de;
        string sFilter = String.Format("(&(objectClass=user)(SAMAccountName={0}))", UserID);
        deSearch.Filter = sFilter;
        deSearch.SearchScope = SearchScope.Subtree;
        SearchResult results = deSearch.FindOne();

感谢。

编辑(使用Mrc_S的建议):

using (adPrincipalContext)
{
    UserPrincipal qbeUser = new UserPrincipal(adPrincipalContext);
    qbeUser.GivenName = "Bruce";
    qbeUser.Surname = "Miller";

    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

    foreach (var found in srch.FindAll())
    {
        UserPrincipal up = (UserPrincipal)found;
        PrincipalSearchResult<Principal> psr = up.GetGroups();                    
        List<Principal> insListPrincipal = new List<Principal>();

        foreach (Principal p in psr)
        {
            insListPrincipal.Add(p);
        } 

        foreach (Principal gp in psr)
        {
            string s1 = gp.Name;
            string s2 = gp.Description;
        }

当我尝试在两个(内部)foreach循环中找到用户所属的组时,在一次迭代后我得到错误。列表(“indListPrincipal”)将包含18个条目,第一个是“域用户”,其余是pricnipal上下文的每个属性的错误。第二次foreach在第一次迭代后就死了。我得到的唯一一个是“域用户”组。似乎整个搜索结果在一次迭代后被释放。我做错了吗?

1 个答案:

答案 0 :(得分:1)

由于您使用的是.NET 3.5及更高版本,因此您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

The UserPrincipal object has quite a selection of properties您可以直接访问 - 如果您需要其他人,您甚至可以根据需要扩展您的UserPrincipal

更新:如果FindByIdentity搜索的各种属性对您来说还不够,请使用PrincipalSearcher并使用“按示例查询”主体进行操作你的搜索:

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a UserPrincipal 
   // and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
   UserPrincipal qbeUser = new UserPrincipal(ctx);
   qbeUser.GivenName = "Bruce";
   qbeUser.Surname = "Miller";
   // of course, you can set **ANY** of the UserPrincipal properties here

   // 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.....          
   }
}