Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

GetUserNameEx (secur32)
 
.
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

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions