Share via


列舉使用者成員資格

本主題包含示範如何使用 Windows 表單來列舉使用者成員資格的資訊與程式碼範例。

建立 Windows 表單以顯示使用者成員資格

  1. 開啟 Visual Studio,然後選取 [新增專案]。

  2. 在 [專案類型] 窗格中,按一下 [Visual C#] 或 [Visual Basic],然後按一下 [範本] 窗格內的 [Windows 應用程式]。****

  3. 為新專案命名,然後按一下 [確定]。

  4. 按一下 [專案 > 加入參考],然後在 [.NET] 索引標籤顯示的清單中按一下 [System.DirectoryServices]。

  5. 在表單設計頁面中,從 [工具箱] 將文字方塊拖曳至表單並設定其格式。這是使用者加入要繫結的使用者名稱的位置。

  6. 將標籤從 [工具箱] 拖曳至表單,並將 [文字] 屬性修改為 [輸入名稱:]。

  7. 將按鈕從 [工具箱] 拖曳至表單,並將 [文字] 屬性修改為 [尋找群組]。

  8. 將 [ListBox] 從 [工具箱] 拖曳到表單。這些結果將顯示在表單中。

  9. 按兩下表單,移至程式碼頁面。

  10. 若要建置 C# 範例,請在 using 陳述式清單結尾加入 "using System.DirectoryServices;" 陳述式。若要建置 Visual Basic 範例,請在 Imports 陳述式清單結尾加入 "Imports System.DirectoryServices" 陳述式。

  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.

Copyright © 2007 by Microsoft Corporation.All rights reserved.