Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.DirectoryServices.AccountManagement;
- using System.DirectoryServices.ActiveDirectory;
- namespace PB.ADUserManagement.Library
- {
- public class ADManager
- {
- private ContextType _Context;
- public ADManager(ContextType context)
- {
- this._Context = context;
- this.StartUp();
- }
- public ADManager()
- {
- this._Context = ContextType.Domain;
- this.StartUp();
- }
- public static string CurrentDomain()
- {
- string name;
- try
- {
- name = Domain.GetCurrentDomain().Name;
- }
- catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException)
- {
- name = Environment.MachineName;
- }
- catch (ActiveDirectoryOperationException activeDirectoryOperationException)
- {
- name = Environment.MachineName;
- }
- return name;
- }
- public ReadOnlyCollection<string> Groups()
- {
- PrincipalSearcher principalSearcher = new PrincipalSearcher()
- {
- QueryFilter = new GroupPrincipal(new PrincipalContext(this._Context))
- };
- PrincipalSearchResult<Principal> principals = principalSearcher.FindAll();
- List<string> strs = new List<string>();
- foreach (Principal principal in principals)
- {
- strs.Add(principal.SamAccountName);
- }
- strs.Sort();
- return new ReadOnlyCollection<string>(strs);
- }
- private static bool IsMemberOfDomain()
- {
- bool flag = false;
- try
- {
- Domain.GetComputerDomain();
- flag = true;
- }
- catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException)
- {
- }
- return flag;
- }
- private void StartUp()
- {
- if (!ADManager.IsMemberOfDomain())
- {
- this._Context = ContextType.Machine;
- }
- }
- internal List<Principal> Users(string groupName)
- {
- PrincipalSearcher principalSearcher = new PrincipalSearcher();
- GroupPrincipal groupPrincipal = new GroupPrincipal(new PrincipalContext(this._Context))
- {
- SamAccountName = groupName
- };
- principalSearcher.QueryFilter = groupPrincipal;
- GroupPrincipal groupPrincipal1 = (GroupPrincipal)principalSearcher.FindOne();
- List<Principal> principals = new List<Principal>();
- principals.AddRange(groupPrincipal1.Members);
- return principals;
- }
- }
- }
High Level Usage is as follows;
var object = new ADManager();
cmbBox cmbBox.DataSource = object.Groups();