Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c# - Get a list of members of a WinNT group

There are a couple of questions similar to this on stack overflow but not quite the same.

I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.

So far I started using the DirectoryEntry object with the WinNT:// provider. This is going ok but I'm stuck on how to get a list of members of a group?

Anyone know how to do this? Or provide a better solution than using DirectoryEntry?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, it's taken a while, messing around with different solutions but the one that fits best with my original question is given below. I can't get the DirectoryEntry object to access the members of a local group using the 'standard' methods, the only way I could get it to enumerate the members was by using the Invoke method to call the native objects Members method.

using(DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
{
    foreach(object member in (IEnumerable) groupEntry.Invoke("Members"))
    {
        using(DirectoryEntry memberEntry = new DirectoryEntry(member))
        {
            Console.WriteLine(memberEntry.Path);
        }
    }
}

I also used a similar technique to add and remove members from the local group.

Hopefully this helps someone else as well. Keith.

EDIT by Tim: added VB.Net version

Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)
    Dim members As New List(Of DirectoryEntry)
    Try
        Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group")
            For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable)
                Dim memberEntry As New DirectoryEntry(member)
                members.Add(memberEntry)
            Next
        End Using
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
    Return members
End Function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...