I was having problems querying Active Directory when using System.DirectoryServices.AccountManagement.UserPrincipal.Current
, so I resorted to using GetUserNameEx
using the NameUserPrincipal
format.
This function receives information about the current user, so it requires that you impersonate yourself if you have not already done so. In C #, this can be done by importing a function:
public 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);
Then call it like this:
string upn = null; StringBuilder userName = new StringBuilder(1024); int userNameSize = userName.Capacity; if (GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameUserPrincipal, userName, ref userNameSize) != 0) { upn = userName.ToString(); }
source share