这可能吗? 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任。)
相关推荐
最新文章