Click here to Skip to main content
15,887,975 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public string GetGroups()
        {

            DirectorySearcher search = new DirectorySearcher(_path);

            //search.Filter = "(&(objectclass=group))";//(cn=%s*)
            search.Filter = "(CN=" + _filterAttribute + ")";
           // search.Filter = "(samaccountname=" + username + ")";
            //search.PropertiesToLoad.Add("memberof");
            StringBuilder groupNames = new StringBuilder();


            try
            {

                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberof"].Count;
                String dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount;
                     propertyCounter++)
                {
                    dn = (String)result.Properties["memberof"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1),
                                      (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " +
                  ex.Message);
            }
            return groupNames.ToString();
        }
    }



hi i m working with active directory lDAP ..i m in a problem that it does not search for the group name ...and in it give search scope function evalutin time out ..plz help me ..i m new to it....
Posted
Updated 4-Feb-13 1:11am
v2

1 solution

Here you go with the method that returns all the group names from AD.
All the best.

C#
            string serverName = string.Empty;
            GlobalCatalog gcServer = null;
            DomainController dc = null;
            try
            {
                dc = DomainController.FindOne(new DirectoryContext(DirectoryContextType.Domain));
                //gcServer = GlobalCatalog.FindOne(new DirectoryContext(DirectoryContextType.Forest));
                serverName = dc.Name;
                //txtProgress.AppendText("\r\nFound Server..." + serverName);
                
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                //this.txtProgress.AppendText("Could not find a Global Catalog.");
                return;
            }

            var groups = GetAllGroupNames(serverName);
....
....
private List<string> GetAllGroupNames(string serverName)
        {
            List<string> groups = new List<string>();
            LdapConnection conn=null;
            int defaultADPageSize = 500;
            int pageCount = 0;
            try
            {
                conn = GetLDAPConnection(serverName);
                string[] propertiesToQuery = { "distinguishedname", "objectguid", "member", "memberof", "objectClass" };
                SearchRequest request = new SearchRequest(
                                                null,
                                                ActiveDirectoryGroupFilterQuery2,
                                                System.DirectoryServices.Protocols.SearchScope.Subtree,
                                                propertiesToQuery);
                // Set the result page size
                PageResultRequestControl requestPageSize = new PageResultRequestControl(defaultADPageSize);
                
                request.Controls.Add(requestPageSize);
                while (true)
                {
                    PageResultResponseControl pageResponse = null;

                    SearchResponse results = (SearchResponse)conn.SendRequest(request);

                    if (null == results)
                    {
                        break;
                    }
                    pageCount++;

                    // verify support for this advanced search operation
                    if (results.Controls.Length != 1 ||
                        !(results.Controls[0] is PageResultResponseControl))
                    {
                        break;
                    }
                    // cast the diretory control into a PageResultResponseControl object.
                    pageResponse = (PageResultResponseControl)results.Controls[0];
                    if (results.Entries.Count > 0)
                    {
                        foreach (SearchResultEntry searchResult in results.Entries)
                        {
                            SearchResultAttributeCollection attColl = searchResult.Attributes;
                            groups.Add(attColl["distinguishedname"][0].ToString());
                        }

                        // if this is true, there are no more pages to request
                        if (pageResponse != null && pageResponse.Cookie.Length == 0)
                        {
                            break;
                        }

                        // set the cookie of the pageRequest equal to the cookie of the pageResponse to
                        // request the next page of data in the send request
                        if (pageResponse != null)
                        {
                            requestPageSize.Cookie = pageResponse.Cookie;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }
            return groups;
        }

private LdapConnection GetLDAPConnection(string server)
        {
            LdapConnection conn = new LdapConnection(string.Format("{0}:{1}", server, "3268"));
            conn.Credential = CredentialCache.DefaultNetworkCredentials;
            conn.AuthType = AuthType.Negotiate;
            conn.SessionOptions.Sealing = true;
            conn.SessionOptions.Signing = true;
            conn.Bind();
            return conn;
        }
</string></string></string>
 
Share this answer
 
Comments
Murali Krishna Babu 9-Apr-13 8:56am    
Hi,

I am also trying to get the members from specified Active Directory Group.

Can you tell me what is "ActiveDirectoryGroupFilterQuery2" in the above solution.

Regards,
Murali.
Kiran Susarla 9-Apr-13 10:53am    
It is an LDAP query similar to mentioned below to retrieve the group details.
string ActiveDirectoryGroupFilterQuery2 = "(|(objectClass=msExchDynamicDistributionList)(objectClass=group))";
Murali Krishna Babu 12-Apr-13 5:19am    
Hi,

I am getting the Compile time error at this line of code

SearchRequest request = new SearchRequest(null, ActiveDirectoryGroupFilterQuery2, System.DirectoryServices.SearchScope.Subtree, propertiesToQuery);

when I specify
string ActiveDirectoryGroupFilterQuery2 = "(|(objectClass=msExchDynamicDistributionList)(objectClass=group))";

Can you help me out.

Regards,
Murali.
Kiran Susarla 12-Apr-13 5:39am    
what is the error you are getting?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900