Enterprise Solutions


How to get full name of logged in user

This article will show you how to use DirectoryServices namespace classes to get full name of logged in user. This technique can be used for both Windows as well as ASP.Net web applications. For ASP.Net application you will have to make sure that you are using Windows authentication along with impersonation turned on.

private void Page_Load(object sender, System.EventArgs e)
{
	WindowsPrincipal p = Thread.CurrentPrincipal as WindowsPrincipal;
	Response.Write(GetFullName(p.Identity.Name));
}

private string GetFullName(string strLogin)
{
	string str = "";
	// Parse the string to check if domain name is present.
	int idx = strLogin.IndexOf('\\');
	if (idx == -1)
	{
		idx = strLogin.IndexOf('@');
	}

	string strDomain;
	string strName;

	if (idx != -1)
	{
		strDomain = strLogin.Substring(0, idx);
		strName = strLogin.Substring(idx+1);
	}
	else
	{
		strDomain = Environment.MachineName;
		strName = strLogin;
	}

	DirectoryEntry obDirEntry = null;
	try
	{
		obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
		System.DirectoryServices.PropertyCollection  coll = obDirEntry.Properties;
		object obVal = coll["FullName"].Value;
		str = obVal.ToString();
	}
	catch (Exception ex)
	{
		str = "";
		Trace.Write(ex.Message);
	}
	return str;
}							
							
Home     About us     Contact us
Copyright    Privacy Policy
Copyright (c) Pardesi Services LLC