Search code examples
.netasp.netactive-directorydirectoryservices

System.DirectoryServices.AccountManagement in .net 2.0


Is there a:

string name = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;

equivalence in .net 2.0 framework? It uses the System.DirectoryServices.AccountManagement (ver 3.5) reference. I tried using that file on a .net 2.0 framework but to no avail.

Basically, I want to retrieve the full username (first name and last name) of the windows user (not Request.ServerVariables["REMOTE_USER"] which only gives windows username)


Solution

  • The S.DS.AM namespace was introduced in .NET 3.5, and unfortunately, there's no 2.0 version of it.

    You can query the current Windows user in an ASP.NET app using WindowsIdentity.GetCurrent().Name - this gives you DOMAIN\UserName.

    Then you'd have to do a user search in AD for that user with a DirectorySearcher object in order to find the corresponding DirectoryEntry. This will give you all the bits and pieces of that user.

        string currentUser = WindowsIdentity.GetCurrent().Name;
    
        string[] domainUserName = currentUser.Split('\\');
        string justUserName = domainUserName[1];
    
        DirectoryEntry searchRoot = new DirectoryEntry("LDAP://dc=(yourcompany),dc=com");
    
        DirectorySearcher ds = new DirectorySearcher(searchRoot);
    
        ds.SearchScope = SearchScope.Subtree;
    
        ds.PropertiesToLoad.Add("sn");
        ds.PropertiesToLoad.Add("givenName");
    
        ds.Filter = string.Format("(&(objectCategory=person)(samAccountName={0}))", justUserName);
    
        SearchResult sr = ds.FindOne();
    
        if (sr != null)
        {
            string firstName = sr.Properties["givenName"][0].ToString();
            string lastName = sr.Properties["sn"][0].ToString();
        }
    

    It's a bit complicated and involved in .NET 2.0 - can't change that :-(

    Marc