views:

82

answers:

5

How can i get the

DomainName\AccountName

as string with the .NET Framework?

+2  A: 

You can use the Environment.UserDomainName property to retrieve the domain and Environment.UserName to retrieve the user name:

Dim domainAndUserName As String _
    = Environment.UserDomainName & "\\" & Environment.UserName
0xA3
Incorrect. Environment.UserDomainName only contains the domain, not the username.
CERIQ
@CERIQ: Sorry, I misread the docs and corrected my answer. Strange that it still received upvotes...
0xA3
A: 

if you are using ASP.NET you can use

HttpContext.Current.User.Identity.Name;
Fahad
+2  A: 
System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString()
Barry
+1, but actually you wouldn't need to call `ToString()` as `Name` is already of type string.
0xA3
@0xA3: Good point - think I got a bit carried away with myself there :-)
Barry
+1  A: 

WindowsIdentity.GetCurrent().Name

Jens Granlund
+1  A: 

Environment.UserDomainName contains the domain/computer name that your account is joined to. Environment.UserName contains only the username. To get the result you're after, you need to concaternate the variables(Environment.UserDomainName & "\\" & Environment.UserName). This only works well in a local context though, if you use this code in a website, you'll get the account name that your application pool is running under. In asp.net, use HttpContext.Current.User.Identity.Name instead.

CERIQ
Before joining domain name and user name first check if the domain name is not empty in case of local users.
Alexander
@Alexander: A local account will have the computer name in the UserDomainName field.
CERIQ