Question

I have the code to get the members of a local group example administrators

private void GetUserGrps()
{
    using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
    {
        foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
        {
            using (DirectoryEntry memberEntry = new DirectoryEntry(member))
            {
                new GUIUtility().LogMessageToFile(memberEntry.Path);
            }
        }
    }

Is there a way to get the groups a local user belongs to using directory services?

Without using Active Directory or domain in it because I want for the local machine only and not for a domain.

Was it helpful?

Solution

Try This

using System.DirectoryServices.AccountManagement;

static void Main(string[] args)
{
    ArrayList myGroups = GetUserGroups("My Local User");
}
public static ArrayList GetUserGroups(string sUserName)
{
    ArrayList myItems = new ArrayList();
    UserPrincipal oUserPrincipal = GetUser(sUserName);

    PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();

    foreach (Principal oResult in oPrincipalSearchResult)
    {
        myItems.Add(oResult.Name);
    }
    return myItems;
}

public static UserPrincipal GetUser(string sUserName)
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();

    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
    return oUserPrincipal;
}
public static PrincipalContext GetPrincipalContext()
{
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
    return oPrincipalContext;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top