如何在给定UserPrincipal对象的情况下从Active Directory获取“公司”和“部门”?

时间:2009-11-23 20:32:57

标签: c# .net active-directory

这可能吗?代码示例会很好。

2 个答案:

答案 0 :(得分:85)

实际上,问题是如何获得.NET 3.5 (System.DirectoryServices.AccountManagement.)UserPrincipal的两个属性 - 没有给出userPrincipalName的对象。

以下是如何使用extension method

执行此操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace MyExtensions
{
    public static class AccountManagementExtensions
    {

        public static String GetProperty(this Principal principal, String property)
        {
            DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
            if (directoryEntry.Properties.Contains(property))
                return directoryEntry.Properties[property].Value.ToString();
            else
                return String.Empty;
        }

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

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

    }
}

上述代码在大多数情况下都适用(即它适用于标准文本/字符串单值Active Directory属性)。您需要修改代码并为您的环境添加更多错误处理代码。

您可以通过将“扩展类”添加到项目中来使用它,然后您可以执行此操作:

PrincipalContext domain = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(domain, "youruser");
Console.WriteLine(userPrincipal.GetCompany());
Console.WriteLine(userPrincipal.GetDepartment());
Console.WriteLine(userPrincipal.GetProperty("userAccountControl"));

(BTW;这对扩展属性非常有用 - too bad it won't be in C# 4 either。)

答案 1 :(得分:14)

如果用户存在部门和公司属性,则应该这样做。

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://dnsNameOfYourDC.my.company.com";
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.PropertiesToLoad.Add("department");
deSearch.PropertiesToLoad.Add("company");

deSearch.SearchScope = SearchScope.Subtree;
deSearch.Filter = "(&(objectClass=User)(userPrincipalName=MyPrincipalName))";
SearchResultCollection results = deSearch.FindAll():

foreach (SearchResult result in results)
{
    ResultPropertyCollection props = result.Properties;
    foreach (string propName in props.PropertyNames)
    {
       //Loop properties and pick out company,department
       string tmp = (string)props[propName][0];
    }
}