views:

50

answers:

1

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 activedirectory or domain in it because i want for the local machine only and not for a domain.

thanks

+1  A: 

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;
}
Raymund