如何获取用户所属组的字符串集合?
if (DomainHelpers.DomainExists(ConnectionString))
{
using(var baseDirectory = new DirectoryEntry(ConnectionString))
{
baseDirectory.Username = Username;
baseDirectory.Password = Password;
using (DirectorySearcher searcher = new DirectorySearcher())
{
searcher.SearchRoot = baseDirectory;
searcher.Filter = "(objectCategory=user)";
searcher.SearchScope = SearchScope.Subtree;
var userResults = searcher.FindAll();
foreach (SearchResult user in userResults)
{
var newUser = new User();
newUser.Name = user.Properties["name"][0].ToString();
newUser.Path = user.Path;
//.Groups is just a List<string>.
newUser.Groups = user.Properties?????
_users.Add(newUser);
}
}
}
}
如何检索用户所属组的集合?
谢谢你! :)
if (DomainHelpers.DomainExists(ConnectionString))
{
using(var baseDirectory = new DirectoryEntry(ConnectionString))
{
baseDirectory.Username = Username;
baseDirectory.Password = Password;
using (DirectorySearcher searcher = new DirectorySearcher())
{
searcher.SearchRoot = baseDirectory;
searcher.Filter = "(objectCategory=user)";
searcher.SearchScope = SearchScope.Subtree;
var userResults = searcher.FindAll();
foreach (SearchResult user in userResults)
{
var newUser = new User();
newUser.Name = user.Properties["name"][0].ToString();
newUser.Path = user.Path;
//.Groups is just a List<string>.
newUser.Groups = user.Properties?????
_users.Add(newUser);
}
}
}
}
How do I retrieve a collection of groups the user belongs to?
Thank you! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要忘记在
...searcher.FindAll()
之前添加searcher.PropertiesToLoad.Add("memberOf");
来填充您的属性:
don't forget to add
searcher.PropertiesToLoad.Add("memberOf");
before...searcher.FindAll()
To populate your property:
您应该使用 System.DirectoryServices.AccountManagement。这容易多了。这是一个很好的代码项目文章,为您提供了有关此中所有类的概述DLL。
使用
DirectoryEntry
确实很难做到正确。首先,获取memberOf
属性并不能为您提供主要组。此外,如果用户拥有来自另一个域的域本地组,则它不会显示在memberOf
属性中。您可以在此处查看详细信息。如果您切换到使用 System.DirectoryServices.AccountManagement,代码如下所示。以下代码可以找到该用户分配到的直接组,其中包括主要组。You should use System.DirectoryServices.AccountManagement. It's much easier. Here is a nice code project article giving you an overview on all the classes in this DLL.
It's really hard to get it right using
DirectoryEntry
. First of all, gettingmemberOf
attribute doesn't give you primary group. Also, if the user has a domain local group from another domain, it won't show up inmemberOf
attribute. You can check here for details. Here is how the code looks like if you switch to use System.DirectoryServices.AccountManagement. The following code can find the immediate groups this user assigned to, which includes the primary group.