如何获得"公司"和"部"从Active Directory给予UserPrincipal对象? [英] How to get "Company" and "Department" from Active Directory given a UserPrincipal object?

查看:288
本文介绍了如何获得"公司"和"部"从Active Directory给予UserPrincipal对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗? code样品将是很好的。

Is this possible? Code sample would be nice.

推荐答案

其实,问题是如何让两个属性的.NET 3.5 (System.DirectoryServices.AccountManagement。)UserPrincipal -object没有给出的UserPrincipalName

Actually, the question was how to get two of the properties for a .NET 3.5 (System.DirectoryServices.AccountManagement.)UserPrincipal-object not given a userPrincipalName.

下面怎么做,与延伸方法

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");
        }

    }
}

以上code在大多数情况下工作(这是它会为标准文本/字符串单值Active Directory属性)。您需要修改code,并添加更多的错误处理code为您的环境。

The above code will work in most cases (that is it will work for standard Text/String Single-Value Active Directory attributes). You'll need to modify the code and add more error handling code for your environment.

您通过添加扩展类到你的项目中使用它,然后你可以这样做:

You use it by add the "Extension Class" to your project and then you can do this:

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"));

(顺便说一句,这将是对延伸属性一个伟大的使用 - 的太糟糕了它不会在C#4任。)

这篇关于如何获得"公司"和"部"从Active Directory给予UserPrincipal对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆