Getting current login from Active Directory using C# code

前端 未结 5 1225
不思量自难忘°
不思量自难忘° 2020-12-23 23:08

How can I get the current user\'s login name from Windows Active Directory using C# code?

相关标签:
5条回答
  • 2020-12-23 23:20

    If you're on .NET 3.5 and up, you can use:

    // set up domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // find current user
    UserPrincipal user = UserPrincipal.Current;
    
    if(user != null)
    {
       string loginName = user.SamAccountName; // or whatever you mean by "login name"
    }    
    

    The new S.DS.AM makes it really easy to play around with users and groups in AD!

    References:

    • Managing Directory Security Principals in the .NET Framework 3.5 (this link has been archived, use this one instead)
    • MSDN docs on System.DirectoryServices.AccountManagement
    0 讨论(0)
  • 2020-12-23 23:28

    I was getting "NT AUTHORITY\NETWORK SERVICE" with other solutions offered but System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString() worked for me.

    0 讨论(0)
  • 2020-12-23 23:36
    System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name
    

    This is also working for me! Thanks

    0 讨论(0)
  • 2020-12-23 23:36

    I have this in my view and works perfectly for me!

    <h5 class="mb-0 text-gray-800">Welcome, <span style="text-transform:capitalize">@User.Identity.Name.Replace("AD-GROUP-NAME\\", "").Replace(".", " ")</span></h5>

    0 讨论(0)
  • 2020-12-23 23:46

    Simply,

    string Name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;
    

    OR

    string Name = System.Environment.UserName  
    

    OR

    string Name = Environment.GetEnvironmentVariable("USERNAME");
    

    OR

    string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    

    works :)

    0 讨论(0)
提交回复
热议问题