Question : C# - Retrieve Active DIrectory Group's Users whose Membership Is PRIMARY

I need to get the all the users of a "Primary Group".  for example, when a do an LDAP Query on "Domain User" members, i get nothing - this is because all the actuall members who belong to it have "Domain Users" as thier primary group - I already figured out how to get a Users Primary Group (Below)  - Now I need to Get that Primary Groups' Members , for example, I pass in Domain Users and I get back user1, user2, etc - Thanks

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
public static string GetUsersPrimaryGroup(string samAccountName)
        {
            try
            {
            
                DirectorySearcher srch = Util.SearchUsers(100, samAccountName, false);
                SearchResult userResult = srch.FindOne();
                DirectoryEntry user = new DirectoryEntry(userResult.Path);
                byte[] userSid = user.Properties["objectSid"][0] as byte[];
                user.RefreshCache(new string[] { "primaryGroupId" });
                int primaryGroupID = (int)user.Properties["primaryGroupId"][0];
                byte[] rid = BitConverter.GetBytes(primaryGroupID);
                for (int i = 0; i < rid.Length; i++)
                {
                    userSid.SetValue(rid[i], new long[] { userSid.Length - (rid.Length - i) });
                }
                string adPath = String.Format("LDAP://<SID={0}>", BuildOctetString(userSid));
                DirectoryEntry de = new DirectoryEntry(adPath);
                //We do not want to dispose untill we have the group name, which is why we assign instead of return
                string primaryGroupName = de.Properties["sAMAccountName"][0].ToString();
                return primaryGroupName;
                
            }
            catch (Exception ex)
            {
                //throw to catch in calling method (we want the details/can trace better)
                throw ex;
            }
           
        }
        
        private static string BuildOctetString(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("X2"));
            }
            return sb.ToString();
        }

Answer : C# - Retrieve Active DIrectory Group's Users whose Membership Is PRIMARY


It should be pretty simple, two parts, first is to retrieve the PrimaryGroupToken value from the group, then execute a search:


DirectorySearcher ADSearch = new DirectorySearcher("(primaryGroupID=" + PrimaryGroupToken + ")");
SearchResultCollection Results = ADSearch.FindAll();


Chris
Random Solutions  
 
programming4us programming4us