GetUserNameEx (secur32)
Last changed: -93.159.254.162

.
Summary
Gets the name of the user or other security principal associated with the calling thread.

C# Signature:

[DllImport("secur32.dll", CharSet=CharSet.Auto)]
public static extern int GetUserNameEx (int nameFormat, StringBuilder userName,
   ref uint userNameSize);

VB Signature:

Declare Function GetUserNameEx Lib "secur32.dll" (nameFormat As Integer, _
   userName As StringBuilder, ByRef userNameSize As Integer) As Integer

User-Defined Types:

None.

Notes:

This may be required because System.Environment.UserDomainName is broken. If the local machine has a user account that is the same name as a logged in domain user (machineName\bob & domainName\bob) UserDomainName returns the machine name, not the domain name.

Tips & Tricks:

Please add some!

Sample Code:

public class Sample

{

      enum EXTENDED_NAME_FORMAT
      {
     NameUnknown = 0,
     NameFullyQualifiedDN = 1,
     NameSamCompatible = 2,
     NameDisplay = 3,
     NameUniqueId = 6,
     NameCanonical = 7,
     NameUserPrincipal = 8,
     NameCanonicalEx = 9,
     NameServicePrincipal = 10,
     NameDnsDomain = 12
      }

      [DllImport("secur32.dll", CharSet=CharSet.Auto)]
      public static extern int GetUserNameEx (int nameFormat, StringBuilder userName, ref int userNameSize);

      public String GetUserDomain()
      {
     if (Environment.OSVersion.Platform != PlatformID.Win32NT)
        return null;

     StringBuilder userName = new StringBuilder(1024);
     int userNameSize = userName.Capacity;

     if(0 != GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameSamCompatible, userName, ref userNameSize))
     {
        string[] nameParts = userName.ToString().Split('\\');
        if (2 != nameParts.Length) return null;
        return nameParts[0];
     }

     return null;
      }

}

Alternative Managed API:

System.Environment.UserName

Documentation