How do I get the first name and last name of the logged in Windows user?

前端 未结 6 1012
独厮守ぢ
独厮守ぢ 2020-12-04 15:53

How I can get my first name last name with c# in my system (logging in windows with Active Directory username and pass)?

Is it possible to do that without going to t

相关标签:
6条回答
  • 2020-12-04 16:06

    Had the same issue. After some research and browsing the Microsoft Docs, I found the solution.

    First install the System.DirectoryServices.AccountManagement package using Nuget Package Manager.

    Then while calling the GetUserNameWithoutDomain method pass the following as the parameters:

    GetUserNameWithoutDomain(UserPrincipal.Current.GivenName, UserPrincipal.Current.Surname); This should definitely work!

    0 讨论(0)
  • 2020-12-04 16:09

    The problem with the approved answer is that if you have a policy of Lastname, Firstname in place, then DisplayName gives Smith, John, not John Smith. There are two ways to get the correct form, the userPrincipal.Name property contains "John Smith (jsmith1)" so you could use this, and just string.Split on "(". Or use the following:

    private string ConvertUserNameToDisplayName(string currentSentencedByUsername)
        {
            string name = "";
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                var usr = UserPrincipal.FindByIdentity(context, currentSentencedByUsername);
                if (usr != null)
                    name = usr.GivenName+" "+usr.Surname;
            }
            if (name == "")
                throw new Exception("The UserId is not present in Active Directory");
            return name;
        }
    

    This would give the required form "John Smith" as required by the original poster.

    0 讨论(0)
  • 2020-12-04 16:14

    There is an easier way to do this:

    using System.DirectoryServices.AccountManagement;
    
    UserPrincipal userPrincipal = UserPrincipal.Current;
    String name = userPrincipal.DisplayName;
    

    enter image description here

    0 讨论(0)
  • 2020-12-04 16:17

    If you're using .Net 3.0 or higher, there's a lovely library that makes this practically write itself. System.DirectoryServices.AccountManagement has a UserPrincipal object that gets exactly what you are looking for and you don't have to mess with LDAP or drop to system calls to do it. Here's all it'd take:

    Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
    // or, if you're in Asp.Net with windows authentication you can use:
    // WindowsPrincipal principal = (WindowsPrincipal)User;
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
    {
        UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
        return up.DisplayName;
        // or return up.GivenName + " " + up.Surname;
    }
    

    Note: you don't actually need the principal if you already have the username, but if you're running under the users context, it's just as easy to pull it from there.

    0 讨论(0)
  • 2020-12-04 16:22

    This solution didn't work for me but this function worked great:

    public static string GetUserFullName(string domain, string userName)
            {
                DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
                return (string)userEntry.Properties["fullname"].Value;
            }
    

    You should call it that way:

    GetUserFullName(Environment.UserDomainName, Environment.UserName);
    

    (Found it here).

    0 讨论(0)
  • 2020-12-04 16:22

    The fastest way is to bind directly to their AD object using their SID, which you already have. For example:

    //ASP.NET
    var identity = (WindowsIdentity) HttpContext.Current.User.Identity;
    
    //Desktop
    var identity = WindowsIdentity.GetCurrent();
    
    var user = new DirectoryEntry($"LDAP://<SID={identity.User.Value}>");
    
    //Ask for only the attributes you want to read.
    //If you omit this, it will end up getting every attribute with a value,
    //which is unnecessary.
    user.RefreshCache(new [] { "givenName", "sn" });
    
    var firstName = user.Properties["givenName"].Value;
    var lastName = user.Properties["sn"].Value;
    
    0 讨论(0)
提交回复
热议问题