views:

1068

answers:

1

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)

+4  A: 

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

marc_s
u r a genius... it worked perfectly many thanks
waqasahmed
I used Request.ServerVariables["REMOTE_USER"] instead of WindowsIdentity.GetCurrent().Name; tho.... but thanks... worked perfectly
waqasahmed
be careful and make sure you dispose your directory entries. they tend to hang around forever and will jam once you run out of concurrent connections.
SillyMonkey
SillyMonkey: good point - this wasn't meant to be "production-grade" code either - just an illustration snippet.
marc_s