Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am receiving an unusual behaviour in my application. I have code that uses Directory Services to find the AD groups for a given, authenticated user. The code goes something like ...

string username = "user"; 
string domain = "LDAP://DC=domain,DC=com"; 
DirectorySearcher search = new DirectorySearcher(domain); 
search.Filter = "(SAMAccountName=" + username + ")"; 

And then I query and get the list of groups for the given user. The problem is that the code was receiving the list of groups as a list of strings. With our latest release of the software, we are starting to receive the list of groups as a byte[].

The system will return string, suddenly return byte[] and then with a reboot it returns string again.

Anyone have any ideas?

code sample:

DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + ldapSearchBase);  
DirectorySearcher userSearcher = new DirectorySearcher(dirEntry)  
  { SearchScope = SearchScope.Subtree,  
    CacheResults = false,  
    Filter = ("(" + txtLdapSearchNameFilter.Text + "=" + userName + ")") 

userResult = userSearcher.FindOne();  
ResultPropertyValueCollection valCol = userResult.Properties["memberOf"];  

foreach (object val in valCol)  
    if (val is string)  
        distName = val.ToString(); 
        distName = enc.GetString((Byte[])val);  
share|improve this question

Since the user is authenticated, you have their token. The token has their complete group memberships. No need to query AD for the groups. (You may need to query to translate the SIDs to friendly names though).

If you're able to impersonate, it's could be as easy as this:

using (WindowsImpersonationContext userImpersonationContext = WindowsIdentity.Impersonate(Request.LogonUserIdentity.Token))  
    WindowsIdentity _identity = WindowsIdentity.GetCurrent();

    IdentityReferenceCollection _adGroups = _identity.Groups;
    StringBuilder _adGroupsSb = new StringBuilder();
    foreach (IdentityReference _group in _adGroups)

    log.Info("User: " + _identity.Name + "; " + _adGroups.Count + " groups: " +
        Environment.NewLine + Environment.NewLine + _adGroupsSb.ToString());

If you're set on querying AD, I would check out using TokenGroups instead of MemberOf. Joe Kaplan's web site has some good examples on this.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.