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