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");
}
}
}
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"));
(BTW; this would have been a great use for Extension Properties – too bad it won’t be in C# 4 either.)