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

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

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

任何人都知道如何做到这一点?或者提供比使用DirectoryEntry更好的解决方案?

有帮助吗?

解决方案

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

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

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

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

蒂姆的

编辑:添加了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提供了一个用于使用Active Directory的标准库: System.DirectoryServices名称空间

Microsoft建议使用System.DirectoryServices命名空间中的两个主要类: DirectoryEntry DirectorySearcher 。在大多数情况下,仅使用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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top