5

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.

riQQ
  • 9,878
  • 7
  • 49
  • 66
user175084
  • 4,550
  • 28
  • 114
  • 169
  • Didn't you ask this question earlier today? -- http://stackoverflow.com/questions/3672602/find-out-user-belongs-to-which-groups – Jemes Sep 09 '10 at 18:51
  • yes but this is another approach.. i need suggestions on it... – user175084 Sep 09 '10 at 19:03
  • 1
    Directory Services is very much tied to LDAP or Active Directory usage. It's not for cycling through your local windows machines users. – NotMe Sep 09 '10 at 19:09
  • @chris.. so how can i get the the groups (Users, Administrators, Guest) of a local user?? – user175084 Sep 09 '10 at 19:30

1 Answers1

8

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
  • 7,684
  • 5
  • 45
  • 78