Skip to content

Instantly share code, notes, and snippets.

@AugustoPedraza
Created March 18, 2014 17:47
Show Gist options
  • Save AugustoPedraza/9625380 to your computer and use it in GitHub Desktop.
Save AugustoPedraza/9625380 to your computer and use it in GitHub Desktop.
Listing users and groups from ActiveDirectory
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