Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for groups a local user is a member of

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.

like image 603
user175084 Avatar asked Sep 09 '10 18:09

user175084


1 Answers

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;
}
like image 192
Raymund Avatar answered Sep 30 '22 06:09

Raymund