Created
October 15, 2012 20:16
-
-
Save henriquegogo/3895095 to your computer and use it in GitHub Desktop.
Get current ActiveDirectory user groups
This file contains hidden or 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; | |
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