我正在使用 Visual Studio 2005 C#。
我正在尝试检索我的 Active Directory 中的用户列表并将它们插入到 DropDownList 控件中。
我可以知道如何提取用户以及如何将它们插入 DropDownList 控制?
编辑:
我希望完成的功能有很多部分。
首先是在 DropDownList 中列出所有用户,并有 2 个复选框,User 和 Admin,并基于分配给的角色DDL 中的用户,相应的复选框将被选中。
选中和取消选中角色复选框也会相应地分配/撤销角色。
最佳答案
如果您使用的是 .NET 3.5 及更高版本,则可以使用 PrincipalSearcher
和“query-by-example”主体进行搜索:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for all users
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.....
}
如果您还没有-绝对阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement
此代码可能会相当慢 - 特别是如果您有一个大型 AD,并且您的 AD 中有大量用户。但话又说回来:在一个下拉列表中列出成千上万的用户真的有帮助吗?您可能需要在那里重新考虑您的策略....
更新:如果您不能使用 .NET 3.5,则必须改用“遗留”DirectorySearcher
类 - 如下所示:
// find your default naming context
DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE");
string defaultCtx = deRoot.Properties["defaultNamingContext"].Value.ToString();
// define a directory searcher for your default context
string searchRootLDAPPath = "LDAP://" + defaultCtx;
DirectoryEntry defaultDE = new DirectoryEntry(searchRootLDAPPath);
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE);
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = "(objectCategory=Person)";
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
// count the user objects found
int count = result.Count;
正如我提到的 - 这将不会在大型 AD 上执行得很好,并且您可能会遇到限制(例如返回的最多 1'000 个用户)和其他问题。您也许应该允许用户搜索用户,例如通过他们的名字或其他东西 - 而不是列出所有您的用户(取决于您的广告的大小)。
关于c# - 如何在 DropDownList 控件中列出 Active Directory 中的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8906367/