Getting the authenticated user’s name when using Windows Authentication with ASP.NET is very simple. I just keep having to go back to Google or dig out an old project to remember it, so here it is:
string username = User.Identity.Name.ToString();
Be sure to add the Security reference:
using System.Web.Security;
Thats it!
[UPDATE] Check out the comments below for some additional suggestions on getting the user name without the Domain name.
Byron
Thanks for the help above though
The above code returns the whole name including the computer name
eg
when i write those codes to my computer i gives me the following result
BROMPO-379477BA\Brian
But i just want to get Brian and not the whole string how will i do that???
Brain,
I’m not sure. I was getting the domain name when I was using it since I was on a LAN with Active Directory running. Since the domain was always the same for my app, I checked for it and replaced it. Sorry I don’t have the answer right now.
BB
Hi Brian,
You try with below code
string strAccount = HttpContext.Current.User.Identity.Name.ToString();
string strUserName = strAccount .Split(“\\”.ToCharArray())[1];
have fun coding,
BB
DirectoryEntry dEntry = new DirectoryEntry(“WinNT://” + Environment.UserDomainName + “/” + Environment.UserName);
return dEntry.Properties[“fullName”].Value.ToString();
@Thang, @AD Guy,
Thanks for the hints!
Byron
Even easier to get the AD user name
my.user.name
The only consistent solution was AD Guys as we use Form Authentication in our project and none of the others would pull the information but that one. We have a need for a seperate part of our application to pull AD Information but sill need Forms Authentication for others and that solution was the only one that worked.
Thanks AD Guy.