代码之家  ›  专栏  ›  技术社区  ›  Anatoli

从Windows服务获取用户所属组的列表

  •  1
  • Anatoli  · 技术社区  · 15 年前

    从Windows服务检索用户所属组列表的最佳方法是什么?

    List<string> groups = new List<string>();
    
    foreach (IdentityReference ir in new WindowsIdentity(name).Groups)
    {
         SecurityIdentifier sid = new SecurityIdentifier(ir.Value);
         NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));
         groups.Add(ntAccount.ToString());
    }
    

    我试图使用上面的代码,但它引发了以下错误。

    Error communicating with client: System.Security.SecurityException: Incorrect function.
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   Raj More    15 年前

    使用LDAP查询访问Active Directory怎么样?

    http://www.codeproject.com/KB/system/activedirquery.aspx

        2
  •  0
  •   Anatoli    15 年前

    下面是我最后使用的代码。我不知道LDAP,但它似乎会引起一些安全问题…

    public static List<string> GetUserGroups(string name)
        {
            List<string> groups = new List<string>();
            DirectorySearcher search = new DirectorySearcher("");
            int groupCount;
            int counter;
            string GroupName;
            string DataToWriteGroups;
    
            search.Filter = "(&(objectClass=user)(SAMAccountName=" + name + "))";
            search.PropertiesToLoad.Add("memberOf");
    
    
            SearchResult result = search.FindOne();
    
    
            groupCount = result.Properties["memberOf"].Count;
    
            if (groupCount > 0)
            {
                DataToWriteGroups = "Group(s) Belongs To User - " + name + "";
                for (counter = 0; counter <= groupCount - 1; counter++)
                {
                    GroupName = "";
                    GroupName = (result.Properties["memberOf"][counter].ToString());
                    groups.Add(GroupName);
                }
            }
    
            return groups;
        }
    
    推荐文章