这可能吗?代码示例会很好.
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
.
这里如何使用扩展方法:>
Here how to do that with an 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 属性).您需要修改代码并为您的环境添加更多错误处理代码.
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 中.)
(BTW; this would have been a great use for Extension Properties - too bad it won't be in C# 4 either.)
这篇关于如何获得“公司"和“部门"从 Active Directory 给定 UserPrincipal 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!