How can I get the current user\'s login name from Windows Active Directory using C# code?
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:
I was getting "NT AUTHORITY\NETWORK SERVICE" with other solutions offered but System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString() worked for me.
System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name
This is also working for me! Thanks
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>
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 :)