枚举用户成员资格

本主题包括说明如何使用 Windows 窗体枚举用户成员资格的信息和代码示例。

创建一个 Windows 窗体以显示用户成员资格

  1. 打开 Visual Studio,然后选择“新建项目”。

  2. 在“项目类型”窗格中,单击“Visual C#”或“Visual Basic”,然后在“模板”窗格中单击“Windows 应用程序”****。

  3. 命名新项目,然后单击“确定”。

  4. 单击“项目”、“添加引用”,然后从 .NET 选项卡上显示的列表中单击“System.DirectoryServices”。

  5. 在窗体设计页中,将一个文本框从工具箱拖到该窗体上并设置它的格式。在此文本框中,用户将添加要绑定到的用户名。

  6. 将一个标签从工具箱拖到窗体上,并且修改 Text 属性以显示“Enter Name:”

  7. 将一个按钮从工具箱拖到窗体上,并且修改 Text 属性以显示“Find Groups”。

  8. 将列表框从工具箱拖到窗体上。结果将显示在窗体中。

  9. 双击此窗体以转到代码页。

  10. 如果生成 C# 示例,则将“using System.DirectoryServices;”语句添加到 using 语句列表的末尾。如果生成 Visual Basic 示例,则将“Imports System.DirectoryServices”语句添加到 Imports 语句列表的末尾。

  11. 将按照此过程得到的代码示例添加到源文件。

  12. 编译并运行该应用程序。

下面的示例说明如何使用 Windows 窗体枚举用户成员资格。

Shared Sub Main() 
    Application.Run(New Form1())
End Sub 'Main

Private Sub label1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 

End Sub 'label1_Click

Private Sub textBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) 

End Sub 'textBox1_TextChanged

Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    Dim strUserADsPath As String = "LDAP://fabrikam/cn=" + textBox1.Text + ",cn=users,dc=fabrikam,dc=com"
    Dim oUser As DirectoryEntry
    oUser = New DirectoryEntry(strUserADsPath)
    listBox1.Items.Add("Groups to which {0} belongs:" + oUser.Name)

    ' Invoke IADsUser::Groups method.
    Dim groups As Object = oUser.Invoke("Groups")
    Dim group As Object
    For Each group In CType(groups, IEnumerable)
        ' Get the Directory Entry.
        Dim groupEntry As New DirectoryEntry(group)
        listBox1.Items.Add(groupEntry.Name)
    Next group
End Sub 'button1_Click


Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 

End Sub 'Form1_Load
static void Main() 
{
    Application.Run(new Form1());
}

private void label1_Click(object sender, System.EventArgs e)
{
}

private void textBox1_TextChanged(object sender, System.EventArgs e)
{
}

private void button1_Click(object sender, System.EventArgs e)
{
    string strUserADsPath = "LDAP://fabrikam/cn=" +textBox1.Text +",cn=users,dc=fabrikam,dc=com";
    DirectoryEntry oUser;
    oUser = new DirectoryEntry(strUserADsPath);
    listBox1.Items.Add("Groups to which {0} belongs:"+ oUser.Name);

    // Invoke IADsUser::Groups method.
    object groups = oUser.Invoke("Groups");
    foreach ( object group in (IEnumerable)groups)   
    {
        // Get the Directory Entry.
        DirectoryEntry groupEntry  = new DirectoryEntry(group);
        listBox1.Items.Add(groupEntry.Name); 
    }
}
private void Form1_Load(object sender, System.EventArgs e)
{
}

另请参见

参考

System.DirectoryServices

概念

用户管理

Send comments about this topic to Microsoft.

版权所有 (C) 2007 Microsoft Corporation。保留所有权利。