查询Active Directory中OU中的所有用户,并将用户名输出到列表框

时间:2011-07-19 17:03:12

标签: c# c#-4.0 active-directory

我需要修改我们添加到架构中的自定义属性,但需要基于所有用户。该属性是MD5哈希,我已经将其存储为公共变量。我正在尝试获取列表框中列出的指定OU中所有用户的列表,以便您可以选择所有用户或单个用户以应用这些值。

这是我目前的Form1.cs代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.DirectoryServices;



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        String Password;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Password = textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(Password);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            Password = s.ToString();

            textBox2.Text = Password;


        }   

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:11)

如果您使用的是.NET 3.5或更高版本,则可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// List of strings for your names
List<string> allUsers = new List<string>();

// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME", 
                                            "OU=SomeOU,dc=YourCompany,dc=com");

// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
   allUsers.Add(found.DisplayName);
}

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement

中的新功能

您可以在UserPrincipal上指定任何属性,并将其用作PrincipalSearcher的“按示例查询”。