获取WinNT组的成员列表

堆栈溢出有几个类似的问题,但不完全相同。

我想在win xp计算机上打开或创建一个本地组,并向其添加成员,域名,本地和众所周知的帐户。 我还想检查一个用户是否已经是一个成员,这样我就不会两次添加同一个帐户,并且可能会出现exception。

到目前为止,我开始将DirectoryEntry对象与WinNT://提供程序一起使用。 这样可以,但是我仍然坚持如何获得一个组成员列表?

有人知道怎么做吗? 或者提供比使用DirectoryEntry更好的解决方案?

好吧,花了一段时间,搞乱了不同的解决方案,但最符合我原始问题的解决方案如下。 我无法使用“标准”方法获取DirectoryEntry对象来访问本地组的成员,我可以通过使用Invoke方法调用本机对象Members方法来枚举成员的唯一方法。

使用(DirectoryEntry groupEntry = new DirectoryEntry(“WinNT://./Administrators,group”))
 {
     foreach((IEnumerable)中的对象成员groupEntry.Invoke(“Members”))
     {
         using(DirectoryEntry memberEntry = new DirectoryEntry(member))
         {
             Console.WriteLine(memberEntry.Path);
         }
     }
 }

我还使用了类似的技术来添加和删除本地组中的成员。

希望这对其他人也有帮助。 基思。

编辑 Tim:添加了VB.Net版本

 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 

Microsoft .NET Framework提供了一个标准库,用于在System.DirectoryServices.dll中使用Active Directory: System.DirectoryServices命名空间

Microsoft建议使用System.DirectoryServices命名空间中的两个主要类: DirectoryEntryDirectorySearcher 。 在大多数情况下,仅使用DirectorySearcher类就足够了。

更新:我在我的机器上测试它 – 它的工作原理。 但也许我误解了你的问题。

以下是一篇优秀的CodeProject文章的示例:

获取属于特定AD组的用户列表

 using System.DirectoryServices; ArrayList GetADGroupUsers(string groupName) { SearchResult result; DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(cn={0})", groupName); search.PropertiesToLoad.Add("member"); result = search.FindOne(); ArrayList userNames = new ArrayList(); if (result != null) { for (int counter = 0; counter < result.Properties["member"].Count; counter++) { string user = (string)result.Properties["member"][counter]; userNames.Add(user); } } return userNames; } 

您应该能够在DirectoryEntry上代表该组的"member"属性中找到此信息。