Home > Deveploment and Programming > How to find users from Active directory using c#

How to find users from Active directory using c#

       

        ArrayList arEmpNames = GetUsersFromAD("Name" + "*");

 

 

       

        public ArrayList GetUsersFromAD(string name)

        {

            ArrayList arEmpName = new ArrayList();

            try

            {

                string userDomain = Environment.UserDomainName;

                using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + userDomain))

                {

                    using (DirectorySearcher dSearch = new DirectorySearcher(entry))

                    {

                        dSearch.Filter = "(&(objectClass=user)(sn=" + name+ "))";

                        foreach (SearchResult sResultSet in dSearch.FindAll())

                        {

                            if (!GetProperty(sResultSet, "samAccountName").Equals(string.Empty) & (!arEmpName.Contains(GetProperty(sResultSet, "samAccountName"))))

                                arEmpName.Add(new DisplayValue(GetProperty(sResultSet, "name") + " [ " + userDomain + "\\" + GetProperty(sResultSet, "samAccountName") + " ] ", userDomain + "\\" + GetProperty(sResultSet, "samAccountName")));

                        }

                        dSearch.Filter = "(&(objectClass=user)(givenname=" + name+ "))";

                        foreach (SearchResult sResultSet in dSearch.FindAll())

                        {

                            if (!GetProperty(sResultSet, "samAccountName").Equals(string.Empty) & (!arEmpName.Contains(GetProperty(sResultSet, "samAccountName"))))

                                arEmpName.Add(new DisplayValue(GetProperty(sResultSet, "name") + " [ " + userDomain + "\\" + GetProperty(sResultSet, "samAccountName") + " ] ", userDomain + "\\" + GetProperty(sResultSet, "samAccountName")));

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: