jump to navigation

Recursively get all users in a group in Active Directory C# June 21, 2012

Posted by vmaceda in Uncategorized.
Tags: ,
1 comment so far

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
using System.DirectoryServices;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;

namespace RecurseUsersInGroups
{
    public partial class FormGroups : Form
    {

        StringBuilder _builder = new StringBuilder();

        public FormGroups()
        {
            InitializeComponent();
        }

        private void buttonGetAllUsers_Click(object sender, EventArgs e)
        {
            try
            {
                textBoxUsers.Clear();
                _builder.Clear();

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, textBoxDomain.Text);
                GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, textBoxADGroup.Text);

                if (grp != null)
                {
                    foreach (Principal p in grp.GetMembers(true))
                    {

                        if (!_builder.ToString().Contains(p.SamAccountName))
                        {
                            _builder.Append(p.SamAccountName);
                            _builder.Append(“; “);
                        }
                    }

                    textBoxUsers.Text = _builder.ToString();

                    grp.Dispose();
                    ctx.Dispose();

                }
                else
                {
                    MessageBox.Show(“\nWe did not find that group in that domain, perhaps the group resides in a different domain?”);
                }
            }
            catch (System.Exception)
            {

                MessageBox.Show(“\nWe did not find that group in that domain, perhaps the group resides in a different domain?”);
            }
           

        }

    }
}