private bool IsMemberOfGroup(string machineName, string memberGroup) { try { string userName = WindowsIdentity.GetCurrent().Name; using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain)) using (UserPrincipal domainUsr = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)) { using (PrincipalContext machineContext = new PrincipalContext(ContextType.Machine, machineName)) using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(machineContext, memberGroup)) using (UserPrincipal localUsr = UserPrincipal.FindByIdentity(machineContext, IdentityType.SamAccountName, userName)) { if (grp != null && domainUsr != null) //local group and domain user { return(grp.GetMembers(true).Contains(domainUsr)); } if (grp != null && localUsr != null) //local group and local user { return(grp.GetMembers(true).Contains(localUsr)); } } } } catch (Exception e) { _logger.Add("Failed getting Is Member of api group", e); } return(false); }
public static void getMembers(string group) { List <PrincipalSearchResult <Principal> > list = new List <PrincipalSearchResult <Principal> >(); try { PrincipalContext LocalMachine = new PrincipalContext(ContextType.Machine); GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(LocalMachine, IdentityType.Name, group); if (gPrincipal != null) { foreach (var y in gPrincipal.GetMembers(true)) { System.Console.WriteLine(y); } } foreach (var y in gPrincipal.GetMembers()) { System.Console.WriteLine(y); } LocalMachine.Dispose(); } catch (PrincipalOperationException ex) { System.Console.WriteLine(ex.Message); } }
public static bool IsUserGroupMember(string userPrincipalName, string groupname, PrincipalContext context) { GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupname); bool foundUser = false; foreach (var member in group.GetMembers(true)) { try { if (member.SamAccountName.Equals(userPrincipalName)) { foundUser = true; break; } } catch (Exception) { foundUser = false; } } group.Dispose(); return(foundUser); }
private bool IsGroupMember(GroupPrincipal g, SecurityIdentifier userSid, HashSet <string> searchedGroups) { if (!(searchedGroups.Add(g.Sid.ToString()))) { return(false); } foreach (var member in g.GetMembers()) { if (member.Sid == userSid) { return(true); } if (member is GroupPrincipal g2) { if (IsGroupMember(g2, userSid, searchedGroups)) { return(true); } } } return(false); }
/// <summary> /// Returns a list of Users for a specified group. /// </summary> /// <param name="groupName">The name of the active directory group.</param> /// <returns></returns> public List <string> ListUsersForGroup(string groupName) { string _groupName = string.Empty; List <string> _members = new List <string>(); // Retrieve the Group principal object for the group you need. // This will verify that the group exists on the specific domain. If gp = null, then it did not find that group. _groupName = groupName.ToString(); GroupPrincipal gp = GroupPrincipal.FindByIdentity(_myContext, _groupName); if (gp != null) { foreach (Principal p in gp.GetMembers(true)) { _members.Add(p.SamAccountName.ToString()); } } if (gp != null) { gp.Dispose(); } return(_members); }
private void UpdateUsers() { try { using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, ActiveDirectorySettings.DefaultDomain)) using (GroupPrincipal memberGroup = GetMembersGroup(principalContext)) { foreach (Guid Id in Users.Select(x => x.Id).Where(x => UserPrincipal.FindByIdentity(principalContext, IdentityType.Guid, x.ToString()) == null)) { Users.Remove(Id); } foreach (string username in memberGroup.GetMembers(true).OfType <UserPrincipal>().Select(x => x.UserPrincipalName).Where(x => x != null)) { using (UserPrincipal principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.UserPrincipalName, username)) { UserModel user = GetUserModelFromPrincipal(principal); if (user != null) { Users.AddOrUpdate(user); } } } } } catch (Exception ex) { LogException(ex); } }
public static IEnumerable <string> GetUsers(string groupName) { var members = new Collection <string>(); using (var ctx = new PrincipalContext(ContextType.Domain, PrincipalHelper.DOMAIN_OFINA)) { GroupPrincipal grp = null; try { grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName); if (grp == null) { throw new InvalidOperationException( "We did not find that group in that domain, perhaps the group resides in a different domain?"); } else { foreach (var p in grp.GetMembers(true)) { members.Add(p.SamAccountName); } } } finally { grp?.Dispose(); } } return(members); }
public List <string> GetGroupMembers(string groupId) { log.Debug("Looking for members of " + groupId); List <string> members = new List <string>(); using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupId)) { if (group == null) { log.Error("Group does not exist: " + groupId); return(null); } else { // argument to GetMembers indicate we want direct members, not indirect members foreach (Principal member in group.GetMembers(false)) { if (member is GroupPrincipal) { continue; } members.Add(member.SamAccountName.ToLower()); } } } } return(members); }
/// <summary> /// Get user names from selected group /// </summary> public static void ListUsersInGroup() { string theUserGroup; try { Console.WriteLine(ContextType.Domain); Console.WriteLine(Environment.UserDomainName); Console.WriteLine(Environment.UserName); // Set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // Find the group in question Console.WriteLine("Input the UserGroup and press Enter"); theUserGroup = Console.ReadLine(); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, theUserGroup); // If found... if (group != null) { // Iterate over members foreach (Principal p in group.GetMembers()) { Console.WriteLine("{0}: {1}, {2}", p.StructuralObjectClass, p.DisplayName, p.SamAccountName); } } Console.WriteLine(); } catch (Exception) { Console.WriteLine("An error occurred..."); } }
public List <string> GetUsers(string groupName) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName); if (group == null) { return(null); } foreach (Principal p in group.GetMembers()) { if (p.StructuralObjectClass == "group") { GetUsers(p.DisplayName); } else { if (!userList.Contains(p.DisplayName)) { userList.Add(p.DisplayName); } } } return(userList); }
public IList <Principal> GetGroupMembers(string domainName, string groupName) { PrincipalContext context = null; if (string.IsNullOrEmpty(domainName)) { context = new PrincipalContext(ContextType.Domain); } else { context = new PrincipalContext(ContextType.Domain, domainName); } GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName); IList <Principal> members = new List <Principal>(); if (group == null) { return(members); } members = group.GetMembers(true).ToList(); return(members); }
public static bool EmptyGroup(string groupname, AdAdminConfig config) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.ServerIpOrDomain, config.AdminAccount, config.AdminPwd); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname); if (group != null) { foreach (Principal p in group.GetMembers()) { UserPrincipal theUser = p as UserPrincipal; if (theUser != null) { group.Members.Remove(theUser); try { group.Save(); } catch (Exception e) { Console.WriteLine(e); } } } return(true); } return(false); }
private void zobrazitUzivatelskeJmenoToolStripMenuItem_Click(object sender, EventArgs e) { if (treeViewGroups.SelectedNode.Parent != null) { runOrStopService("RemoteRegistry", textBoxComputername.Text, serviceAction.run); //ServiceManipulation.runOrStopService("RemoteRegistry", textBoxComputername.Text, ServiceManipulation.serviceAction.run); registryFix(textBoxComputername.Text); string selectedUser = treeViewGroups.SelectedNode.Text; string selectedGroup = treeViewGroups.SelectedNode.Parent.Text; try { //Removing selected user from opened group using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, textBoxComputername.Text)) using (GroupPrincipal localGroup = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, selectedGroup)) foreach (Principal groupUser in localGroup.GetMembers()) { if (groupUser.SamAccountName == selectedUser) { MessageBox.Show(groupUser.Name, groupUser.SamAccountName, MessageBoxButtons.OK); } } } catch (System.DirectoryServices.DirectoryServicesCOMException E) { MessageBox.Show(E.Message.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error); } runOrStopService("RemoteRegistry", textBoxComputername.Text, serviceAction.stop); //ServiceManipulation.runOrStopService("RemoteRegistry", textBoxComputername.Text, ServiceManipulation.serviceAction.stop); } }
public static List <string> GetADSecurityGroupUsers(String sgAlias) { List <string> userList = new List <string>(); using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, sgAlias); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { userList.Add(p.SamAccountName); Console.WriteLine(p.SamAccountName); } grp.Dispose(); ctx.Dispose(); } else { Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?"); } } return(userList); }
public static List <string> GetAllUsers(string domain, string group) { if (string.IsNullOrWhiteSpace(group)) { return(GetAllUsers(domain)); } var users = new List <string>(); using (var ctx = new PrincipalContext(ContextType.Domain, domain)) { GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, group); if (grp != null) { foreach (Principal p in grp.GetMembers()) { if (p is UserPrincipal) { users.Add((p as UserPrincipal).SamAccountName); } } } else { LogManager.GetLogger(typeof(ActiveDirectoryHelper)).Debug($"Active Directory Group '{group}' not found under '{domain}' domain"); } } return(users); }
public List <string> EnumGroupEmails(string groupName, string domainName) { List <string> emails = new List <string>(); try { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName)) { using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName)) { var sams = from x in grp.GetMembers(true) select new { x.SamAccountName, }; var users = from sam in sams.Distinct() let usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sam.SamAccountName) select new { usr.SamAccountName, usr.DisplayName, usr.EmailAddress }; foreach (var u in users) { if (u.EmailAddress != null) { Console.WriteLine("Adding " + u.DisplayName + ": " + u.EmailAddress); emails.Add(u.EmailAddress); } } } } } catch (Exception e) { Console.WriteLine("Error getting emails: " + e.Message); } return(emails); }
private async Task SearchGroupAsync() { var sw = Stopwatch.StartNew(); PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, _adGroup); var users = new List <PrincipalContainer>(); if (group != null) { try { foreach (var p in group.GetMembers()) { users.Add(new PrincipalContainer(p)); } SetStatus("{0} user{1} found. Time: {2} ms", users.Count, users.Count == 1 ? "" : "s", sw.ElapsedMilliseconds); } catch (Exception ex) { Logger.Log(ex); SetStatus("Error occurred: {0}. More info in log file \"{1}\"", ex.Message, Logger.GetLogFileName()); } } else { SetStatus("No group called \"{0}\" was found", _adGroup); } if (null != users) { Members = users.OrderBy(p => p.DisplayName); } sw = null; Searching = false; }
private void buttonGetGroup_Click(object sender, EventArgs e) { // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain, addomain); // find the group in question GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupcomboBox.Text); try { // if found.... if (group != null) { frm1.OutputBox.AppendText("Members of " + groupcomboBox.Text + ":"); // iterate over members foreach (Principal p in group.GetMembers()) { frm1.OutputBox.AppendText("\r\n"); frm1.OutputBox.AppendText(p.DisplayName.ToString()); } frm1.OutputBox.AppendText("\r\n"); frm1.OutputBox.AppendText("\r\n"); frm1.OutputBox.AppendText("############"); } } catch (SystemException err) { System.Windows.Forms.MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } this.Close(); }
public void ADGetUsersInGroup(string strGroup, List <string> listUserNames) { try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, this.Domain); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, strGroup); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { listUserNames.Add(p.SamAccountName); } grp.Dispose(); ctx.Dispose(); } else { MessageBox.Show("The group [" + strGroup + "] was not found in the Active Direcotry.", "ADGetUsersInGroup(): Error Connecting to Active Directory"); } } catch (System.Exception x) { Jrfc.Exception.HandleException(x); } }
public static bool IsInGroup(string groupname) { try { ContextType type = ContextType.Domain; if (!groupname.Contains("\\")) { type = ContextType.Machine; } PrincipalContext context = new PrincipalContext(type); GroupPrincipal group = GroupPrincipal.FindByIdentity( context, groupname); if (group != null) { return(group.GetMembers(true).Contains(UserPrincipal.Current)); } else { return(false); } } catch (Exception ex) { Logger.Log.Error(ex); return(false); } }
/// <summary> /// The adGroup parameter value is the AD group display name. /// </summary> /// <param name="adGroup">Default Value is "G-S-DSHS DCS IT Service Desk"</param> /// <returns></returns> public static List <string> GetGroupMembers(string adGroup) { List <string> members = new List <string>(); using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { try { // find the group in question GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, adGroup); // if found.... if (group != null) { // iterate over the group's members foreach (Principal p in group.GetMembers()) { members.Add(p.DisplayName); } } } catch (Exception ex) { /* Just let it fall through.*/ } } return(members); }
private bool IsMemberOfADGroup(string userName, string groupName) { bool isMember = false; //List<string> grpMembers = new List<string>(); using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { //UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName); if (group != null) { foreach (Principal p in group.GetMembers(true)) { if (p.SamAccountName.ToUpper() == userName.ToUpper()) { isMember = true; break; } } } group.Dispose(); } return(isMember); }
private void EscalateReturn_Load(object sender, EventArgs e) { string groupName = "Domain Users"; string domainName = "192.168.10.5"; //get AD users PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName); try { foreach (Principal p in grp.GetMembers(false)) { if (p.DisplayName != null) { comboBox1.Items.Add(p.DisplayName); } } grp.Dispose(); ctx.Dispose(); } catch { MessageBox.Show("Server not available. Check internet connection"); } comboBox1.Sorted = true; }
//Pass a group name as a parameter and returns user information public List <Employee> GetUserPerByAdGroup(string gName) { var userList = new List <Employee>(); sDomain = this.DomanName; using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, sDomain)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, gName); if (group != null) { // iterate over the group's members foreach (Principal p in group.GetMembers()) { //Initializing an object which will be called mostly to populate user dropdown lists var user = UserPrincipal.FindByIdentity(ctx, p.SamAccountName); var employeeObject = new Employee(); try { employeeObject.EmployeeFirstName = string.IsNullOrWhiteSpace(user.GivenName) ? user.Name : user.GivenName; employeeObject.EmployeeSurname = user.Surname; employeeObject.EmployeeNumber = user.VoiceTelephoneNumber; employeeObject.EmailAddress = user.EmailAddress; employeeObject.UserName = p.SamAccountName; employeeObject.DisplayName = user.GivenName + " " + user.Surname; //Adding an object to a class if (!string.IsNullOrWhiteSpace(employeeObject.DisplayName)) { userList.Add(employeeObject); } } catch (Exception) { } } } } //There are instances (for example raters) where a group becomes a user hence a group list is appended into a user information var ADGroupList = new ADUsers().GetAdGroupsForUser(Generic.GetCurrentLogonUserName(), new ADUsers().DomanName); for (int i = 0; i < ADGroupList.Count; i++) { userList.Add(new Employee() { DisplayName = ADGroupList[i] }); } return(userList.OrderBy(c => c.DisplayName).ToList()); }
public static int UpdateGroupUsers(string groupName, List <string> usersName) { List <string> addedUsers = new List <string>(); int retAddCount = 0; GroupPrincipal qbeGroup = CreateGroup(groupName, false); foreach (UserPrincipal user in qbeGroup.GetMembers()) { if (usersName.Contains(user.Name)) { addedUsers.Add(user.Name); retAddCount++; } else { user.Delete(); } } foreach (string addedUserName in addedUsers) { usersName.Remove(addedUserName); } foreach (string addUserName in usersName) { bool isSuccess = CreateLocalWindowsAccount(addUserName, "password", addUserName, "", groupName, false, false); if (isSuccess) { retAddCount++; } } return(retAddCount); }
public override string[] GetUsersInRole(string roleName) { if (!HAP.Web.Configuration.hapConfig.Current.AD.UseNestedLookups) { return(wtrp.GetUsersInRole(roleName)); } else if (HttpContext.Current.Cache["rolecache-" + roleName.ToLower()] == null) { PrincipalContext pcontext; if (HAP.Web.Configuration.hapConfig.Current.AD.SecureLDAP) { pcontext = new PrincipalContext(ContextType.Domain, HAP.Web.Configuration.hapConfig.Current.AD.UPN, null, ContextOptions.Negotiate, HAP.Web.Configuration.hapConfig.Current.AD.User, HAP.Web.Configuration.hapConfig.Current.AD.Password); } else { pcontext = new PrincipalContext(ContextType.Domain, HAP.Web.Configuration.hapConfig.Current.AD.UPN, HAP.Web.Configuration.hapConfig.Current.AD.User, HAP.Web.Configuration.hapConfig.Current.AD.Password); } GroupPrincipal gp = GroupPrincipal.FindByIdentity(pcontext, roleName); if (gp == null) { return new string[] { } } ; List <string> users = new List <string>(); foreach (Principal p in gp.GetMembers(true)) { users.Add(p.Name); } HttpContext.Current.Cache.Insert("rolecache-" + roleName.ToLower(), users.ToArray(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); } return(HttpContext.Current.Cache["rolecache-" + roleName.ToLower()] as string[]); }
/// <summary> /// Retrieve listing of all users in a specified role. /// </summary> /// <param name="rolename">String array of users</param> /// <returns></returns> public override string[] GetUsersInRole(String rolename) { if (!RoleExists(rolename)) { throw new ProviderException(String.Format("The role '{0}' was not found.", rolename)); } using (PrincipalContext context = new PrincipalContext(ContextType.Domain, _domain)) { try { GroupPrincipal p = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, rolename); return(( from user in p.GetMembers(true) where !_usersToIgnore.Contains(user.SamAccountName) select user.SamAccountName ).ToArray()); } catch (Exception ex) { // TODO: LogError( "Unable to query Active Directory.", ex ); return(new[] { "" }); } } }
public List <String> QueryADGroupMembers(String sGroup) { List <String> ListADGroupMembers = new List <String>(); try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain); GroupPrincipal grpObj = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, sGroup); if (grpObj != null) { foreach (Principal p in grpObj.GetMembers(true)) { String sObjName = p.SamAccountName.ToString().Trim(); if (sObjName.Substring(sObjName.Length - 1, 1) == "$") { sObjName = sObjName.Substring(0, sObjName.Length - 1); } ListADGroupMembers.Add(sObjName); } grpObj.Dispose(); ctx.Dispose(); } return(ListADGroupMembers); } catch (Exception ex) { WriteBuffer("Error source: QueryADGroupMembers()" + " " + ex.Message); return(ListADGroupMembers); } }
/// <summary> /// Provides the domain user full details. /// </summary> /// <param name="domainName">Name of the domain.</param> /// <returns></returns> public static DataSet ProvideDomainUserFullDetails(string domainName, string sessionID, string userSource, string defaultDepartment, string fullNameAttribute) { DataSet UsersList = new DataSet(); UsersList.Tables.Add(); UsersList.Tables[0].Columns.Add("REC_SYSID", typeof(string)); UsersList.Tables[0].Columns.Add("USER_ID", typeof(string)); UsersList.Tables[0].Columns.Add("SESSION_ID", typeof(string)); UsersList.Tables[0].Columns.Add("USR_SOURCE", typeof(string)); UsersList.Tables[0].Columns.Add("USR_ROLE", typeof(string)); UsersList.Tables[0].Columns.Add("DOMAIN", typeof(string)); UsersList.Tables[0].Columns.Add("FIRST_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("LAST_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("EMAIL", typeof(string)); UsersList.Tables[0].Columns.Add("RESIDENCE_ADDRESS", typeof(string)); UsersList.Tables[0].Columns.Add("COMPANY", typeof(string)); UsersList.Tables[0].Columns.Add("STATE", typeof(string)); UsersList.Tables[0].Columns.Add("COUNTRY", typeof(string)); UsersList.Tables[0].Columns.Add("PHONE", typeof(string)); UsersList.Tables[0].Columns.Add("EXTENSION", typeof(string)); UsersList.Tables[0].Columns.Add("FAX", typeof(string)); UsersList.Tables[0].Columns.Add("DEPARTMENT", typeof(string)); UsersList.Tables[0].Columns.Add("USER_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("CN", typeof(string)); UsersList.Tables[0].Columns.Add("DISPLAY_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("FULL_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("C_DATE", typeof(string)); UsersList.Tables[0].Columns.Add("REC_ACTIVE", typeof(string)); UsersList.Tables[0].Columns.Add("AD_PIN", typeof(string)); UsersList.Tables[0].Columns.Add("AD_CARD", typeof(string)); string cardValue = ""; string pinValue = ""; int valuesCount = 0; PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Constants.DOMAIN_USERS); if (group != null) { foreach (Principal principal in group.GetMembers(false)) { string userName = principal.SamAccountName; string department = ""; if (string.IsNullOrEmpty(department)) { department = defaultDepartment; } UsersList.Tables[0].Rows.Add(valuesCount, principal.SamAccountName, sessionID, userSource, "User", domainName, principal.Name, "", principal.UserPrincipalName, "", "", "", "", "", "", "", department, userName, "", principal.DisplayName, principal.SamAccountName, DateTime.Now.ToString(), "True", pinValue, cardValue); valuesCount++; } group.Dispose(); context.Dispose(); } return(UsersList); }
static void ReaadAD() { string groupName = "Domain Admins"; Console.Write("Domain: "); string domainName = Console.ReadLine(); Console.Write("Username: "******"Password: "******""; GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName); if (grp != null) { foreach (Principal p in grp.GetMembers(false)) { Console.WriteLine(p.SamAccountName + " - " + p.DisplayName); } grp.Dispose(); //Console.ReadLine(); } else { Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?"); //Console.ReadLine(); } // define a "query-by-example" principal - here, we search for a GroupPrincipal UserPrincipal qbeGroup = new UserPrincipal(ctx); // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(qbeGroup); // find all matches foreach (UserPrincipal found in srch.FindAll()) { Console.WriteLine(found.Name); foreach (GroupPrincipal g in found.GetGroups(ctx)) { Console.WriteLine("\t{0}", g.Name); } // do whatever here - "found" is of type "Principal" - it could be user, group, computer..... } }