Skip to content

Instantly share code, notes, and snippets.

@dvhthomas
Created October 4, 2009 05:54
Show Gist options
  • Save dvhthomas/201181 to your computer and use it in GitHub Desktop.
Save dvhthomas/201181 to your computer and use it in GitHub Desktop.
Getting username from Active Directory
using System;
using System.DirectoryServices;
using System.Security.Principal;
using System.Web.UI;
namespace BookWeb
{
public partial class Main : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
string fullname = GetFullName(Page.User);
lblName.Text = fullname;
}
private static string GetFullName(IPrincipal user)
{
string name = string.Empty;
if (user == null) return name;
string ldapName = user.Identity.Name.Split('\\')[1];
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=Woolpertinc,DC=local");
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = string.Format("(sAMAccountName={0})", ldapName);
searcher.PropertiesToLoad.Add("givenName"); // given, or first, name
searcher.PropertiesToLoad.Add("sn"); // surname
SearchResult result = searcher.FindOne();
if (result != null)
{
name = string.Format("{0} {1}", result.Properties["givenName"][0], result.Properties["sn"][0]);
}
return name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment