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

前端 未结 6 1031
独厮守ぢ
独厮守ぢ 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: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://");
    
    //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;
    

提交回复
热议问题