How do I get the current windows user's name in username@domain format?

Tony Vitabile picture Tony Vitabile · Aug 28, 2012 · Viewed 34.1k times · Source

I know that the following function returns the current Windows user's name in domain\username format.

Convert.ToString( WindowsIdentity.GetCurrent().Name );

But how do I obtain the user's name in username@domain format?

EDIT:

I'm responding in this edit as everyone who has replied has the same basic idea.

From what I've been given to understand, parsing the name from domain\username format and constructing it as username@domain is not safe or advised. I believe this is so because there is no guarantee that the two domain names are the same in the different formats. For example, in the company where I work, the domain part of the domain\username format is based upon deparment, but in the username@domain, it's the company name. It's the kind of thing that requires a DNS lookup.

I was hoping that there was an API that did this DNS lookup. I guess I should have put this information into my original question. Sorry.

Answer

Kevin picture Kevin · Aug 28, 2012

Something like this should work...

string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\');
string userName = temp[1] + "@" + temp[0];