I encountered a apparently simple problem but which is giving me some trouble.
Let's suppose I have two trusted AD domains: DEMO.intern and DEMO.trust
I need to get the FQDN for the current user in my app which uses Windows auth. Users from both domains can use it. I need to know which user comes from which domain.
Obviously,
Environment.UserDomainName
or
System.Security.Principal.WindowsIdentity.GetCurrent().Name
fails returning DEMO in both cases.
I know that:
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName
gives me the full domain name for the local computer but how can this be achieved for the current logged in user?
I also tried:
var host = Dns.GetHostEntry(Environment.UserDomainName);
host.HostName.Dump();
with no success giving me the error "No such host is known". So how can I obtain the full domain name for the logged in user for example DEMO.intern not just DEMO?
After some research, this gets the job done:
public static class GetUserNameExUtil
{
#region Interop Definitions
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,
}
[System.Runtime.InteropServices.DllImport("secur32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize);
#endregion
public static string GetUserName(EXTENDED_NAME_FORMAT nameFormat)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
return null;
}
StringBuilder userName = new StringBuilder(1024);
int userNameSize = userName.Capacity;
if (GetUserNameEx((int)nameFormat, userName, ref userNameSize) != 0)
{
string[] nameParts = userName.ToString().Split('\\');
return nameParts[0];
}
return null;
}
public static string GetUserFullName()
{
return GetUserName(EXTENDED_NAME_FORMAT.NameDnsDomain);
}
}