Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
Hi Team

There are 2 thing username and name of that user. we can get username by
C#
Environment.GetEnvironmentVariable("USERNAME");


But how should we get the name of that user(considering both are different)

Thanks in advance

Regards
Arihant
Posted
Updated 27-Jan-11 3:31am
v2

1 solution

Have a look at System.Security.Principal;

e.g.

C#
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
Console.WriteLine(principal.Identity.Name);
Console.WriteLine(string.Format("User is administrator = {0}", principal.IsInRole("Administrators")));


You could then query Active Directory to retrieve additional information about the user

C#
using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
       adSearch.PropertiesToLoad.Add("sn");  // surname = last name
       adSearch.PropertiesToLoad.Add("givenName");  // given (or first) name
       adSearch.PropertiesToLoad.Add("mail");  // e-mail addresse
       adSearch.PropertiesToLoad.Add("telephoneNumber");  // phone number


     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}
 
Share this answer
 
v2
Comments
ArihantShyamsukha 25-Jan-11 9:08am    
Sir
This give me same result as code which i have provided. In my system my userid is stored as abc_def but my name is stored as abc k def
where abc is first name , k is middle name and def is lasname
Dylan Morley 25-Jan-11 9:13am    
Are you using Active Directory?
ArihantShyamsukha 27-Jan-11 5:14am    
YES
Dylan Morley 27-Jan-11 9:27am    
Then query AD to get the info you need, see updated answer
Manfred Rudolf Bihy 27-Jan-11 17:09pm    
Proposed as answer! 5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900