How can I get the current user's login name from Windows Active Directory using C# code?
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 :)
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:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name
This is also working for me! Thanks
I was getting "NT AUTHORITY\NETWORK SERVICE" with other solutions offered but System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString() worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With