Search code examples
c#directorydirectoryservices

C# - How do I Get a users "Web Page" property from Active Directory?


using System.DirectoryServices.AccountManagement;

string WebPage = "";
using (var context = new PrincipalContext(ContextType.Domain))
{
    var usr = UserPrincipal.FindByIdentity(context, System.Environment.UserName);
    if (usr != null)
        WebPage = usr.???????????;
}

I am able to get things like GivenName or EmailAddress, but the Web Page property is not an option. I am just using the Web Page property to store the users Slack channel ID for direct messages and would prefer not to repurpose the VoiceTelephoneNumber property, which I can acquire and have tested as working. Thanks in advance!


Solution

  • For any attribute that is not exposed by the UserPrincipal class, you can use GetUnderlyingObject(), which returns the underlying DirectoryEntry object, then get the attribute from the Properties collection. Like this:

    WebPage = ((DirectoryEntry) usr.GetUnderlyingObject()).Properties["wWWHomePage"].Value;
    

    This is one reason I don't bother with UserPrincipal at all. I have to resort to DirectoryEntry sometimes anyway. But also because of performance, which I wrote an article about: Active Directory: Better performance