Created
March 18, 2014 17:47
-
-
Save AugustoPedraza/9625380 to your computer and use it in GitHub Desktop.
Listing users and groups from ActiveDirectory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.DirectoryServices.AccountManagement; | |
using System.Linq; | |
namespace AugustoPedraza.Utils | |
{ | |
public class ActiveDirectory | |
{ | |
public static string Domain { get; set; } | |
public static IEnumerable<string> GetAllUsers() | |
{ | |
return GetObject<UserPrincipal>(); | |
} | |
public static IEnumerable<string> GetAllGroups() | |
{ | |
return GetObject<GroupPrincipal>(); | |
} | |
private static IEnumerable<string> GetObject<T>() where T: Principal | |
{ | |
var principalContext = new PrincipalContext(ContextType.Domain, Domain); | |
var itemPrincipal = (T)Activator.CreateInstance(typeof(T), new object[] { principalContext }); | |
var searcher = new PrincipalSearcher(itemPrincipal); | |
return searcher.FindAll().OfType<T>().Select(x => x.SamAccountName).OrderBy(x => x); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment