- 1 year ago
How to get the dynamic user groups of the active windows user?
Comment
1 / 1
To get the dynamic user groups of the active Windows user, you can use the System.DirectoryServices.AccountManagement
namespace in C#/.NET. Here's an example:
csharpusing System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main(string[] args)
{
// Get the current Windows user
string userName = Environment.UserName;
// Create a principal context for the current domain
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
// Find the user by username
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
if (user != null)
{
// Get the user's group membership
PrincipalSearchResult<Principal> groups = user.GetGroups();
Console.WriteLine("Dynamic Groups for User: " + user.Name);
Console.WriteLine("------------------------------");
foreach (Principal group in groups)
{
// Filter out static groups (security groups)
if (group is GroupPrincipal dynamicGroup)
{
Console.WriteLine(dynamicGroup.Name);
}
}
}
}
Console.ReadLine();
}
}
This code retrieves the current Windows user, creates a PrincipalContext
for the domain, and finds the user by their username. Then, it retrieves the user's group membership using the GetGroups()
method. It filters out static groups (security groups) and displays the dynamic groups to which the user belongs.
Make sure to add a reference to the System.DirectoryServices.AccountManagement
assembly in your project.