Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Created October 15, 2012 20:16
Show Gist options
  • Save henriquegogo/3895095 to your computer and use it in GitHub Desktop.
Save henriquegogo/3895095 to your computer and use it in GitHub Desktop.
Get current ActiveDirectory user groups
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Security.Principal;
namespace console
{
class MainClass
{
public static void Main (string[] args)
{
var groups = CurrentUserGroups();
var groupsString = string.Join(", ", groups);
Console.Write(groupsString + "\n");
}
private static IEnumerable<GroupPrincipal> CurrentUserGroups()
{
var result = new List<GroupPrincipal>();
var groups = CurrentUser().GetAuthorizationGroups();
result.AddRange(groups.OfType<GroupPrincipal>());
return result;
}
private static UserPrincipal CurrentUser()
{
var context = new PrincipalContext(ContextType.Domain);
var currentUserName = WindowsIdentity.GetCurrent().Name;
var user = UserPrincipal.FindByIdentity(context, currentUserName);
return user;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment