Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current login from Active Directory using C# code

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

like image 735
Sunil Mathari Avatar asked Jun 04 '12 07:06

Sunil Mathari


4 Answers

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

like image 155
Ahmed Ghoneim Avatar answered Nov 11 '22 22:11

Ahmed Ghoneim


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
like image 28
marc_s Avatar answered Nov 11 '22 21:11

marc_s


System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name

This is also working for me! Thanks

like image 3
Singaravelan Avatar answered Nov 11 '22 21:11

Singaravelan


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

like image 2
Tel Avatar answered Nov 11 '22 23:11

Tel