public string GetGroups(string username) { DirectorySearcher search = new DirectorySearcher(path); search.Filter = "(cn=" + filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); using (HostingEnvironment.Impersonate()) { try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count, equalIndex, commaIndex; string dn, grp; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (string)result.Properties["memberOf"][propertyCounter]; equalIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalIndex) { return(null); } grp = dn.Substring((equalIndex + 1), (commaIndex - equalIndex) - 1); // Retrieves the Group Name in Active Directory if (grp.Contains("MRReports") || grp.Contains("CUReports")) // if group name contains the following conditions, add it to group names and append a back slash { groupNames.Append(grp); groupNames.Append("|"); } } groupNames.Append(filterAttribute); // append the user's display name after the list of groups } catch (Exception ex) { RunStoredProcedure rsp = new RunStoredProcedure(); string groups = rsp.GetGroupNames(username); if (!string.IsNullOrEmpty(groups)) { // link the stored procedure created in db string name = rsp.GetName(username); groupNames.Append(groups); groupNames.Append("|"); groupNames.Append(name); } else { throw new Exception("Error obtaining group names. " + ex.Message); } } return(groupNames.ToString()); } }