Getting current login from Active Directory using C# code

Sunil Mathari picture Sunil Mathari · Jun 4, 2012 · Viewed 59.4k times · Source

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

Answer

Ahmed Ghoneim picture Ahmed Ghoneim · Jun 4, 2012

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 :)