来自AccountManagement.Principal的搜索者组属性的Active Directory

时间:2013-08-01 12:26:45

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

我在.NET 4.5中使用System.DirectoryServices.AccountManagement。

我正在尝试从Active Directory获取所有组和属性,如下面的代码。但我有其他属性,因为Key Value是System.DirectoryServices.SearchResult,

如何从System.DirectoryServices.AccountManagement.Principal

获取System.DirectoryServices.SearchResult下的所有属性
// create your domain context
var ctx = new PrincipalContext(ContextType.Domain, _domain, _userName, _password);

// define a "query-by-example" principal - here, we search for a GroupPrincipal 
 var groupPrincipal = new GroupPrincipal(ctx);
// create your principal searcher passing in the QBE principal    
var searcher = new PrincipalSearcher(groupPrincipal);
foreach (var found in searcher.FindAll())
{
}

1 个答案:

答案 0 :(得分:0)

我已用扩展方法解决了这个问题,如下所示,但建议我是否有任何有效的方法来做同样的工作。

 public static class AccountManagementExtensions
    {
        public static String GetProperty(this Principal principal, String property)
        {
            var directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
            return directoryEntry != null && directoryEntry.Properties.Contains(property)
                       ? directoryEntry.Properties[property].Value.ToString()
                       : String.Empty;
        }

        public static String GetCompany(this Principal principal)
        {
            return principal.GetProperty("company");
        }

        public static String GetDepartment(this Principal principal)
        {
            return principal.GetProperty("department");
        }
    }