Get Full Name of current Thread Principal

We often get questions about how to get the "full name" of the current user. This wraps the GetUserNameEx API to return same. Also shown is an alternate method using DirectoryServices with domain and username input parameters.

using System;
using System.Text;
using System.Runtime.InteropServices ;

namespace PAB.Utils
{
/// <summary>
/// Wraps the GetUserNameEx API in secur32.dll, using the NameDisplay enum (3)
/// <remarks>
/// Usage:private void Page_Load(object sender, System.EventArgs e)
///{
/// PAB.Utils.GetUserNameExUtil u= new PAB.Utils.GetUserNameExUtil();
/// string s2=u.GetUserFullName();
/// this.Label1.Text=s2;
///}
/// </remarks>
/// </summary>
public class GetUserNameExUtil
{
public GetUserNameExUtil()
{
}
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 GetUserFullName()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return null;
StringBuilder userName = new StringBuilder(1024);
int userNameSize = userName.Capacity;
if(0 != GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameDisplay, userName, ref userNameSize))
{
string[] nameParts = userName.ToString().Split('\\');
return nameParts[0];
}
return null;
}
}
}

And here is how to do it for any domain and user, with DirectoryServices:

public string GetUserFullNameDs( string domain, string userName)
{

DirectoryEntry userEntry = new DirectoryEntry("WinNT://" +domain +"/"+userName +",User");
return (string)userEntry.Properties["fullname"].Value;
}


Submission Date:  1/26/2006 11:50:11 AM
Submitted By:  Peter Bromberg
My Home Page:  http://www.eggheadcafe.com

By Peter Bromberg   Popularity  (824 Views)