If ever you need to make some applications for users of your active directory using C# windows forms/windows service and you want to use their Active Directory details you may refer to this post.

  • Reference: ​http://snipplr.com/view/53632/get-a-windows-active-directory-user-display-name/
  • Namespace: System.DirectoryServices.AccountManagement on your references

Now for my version, here’s how I used it to get the UserName value and pass into it:


private string LoadUser()
{

string userName = Environment.UserName;

if (!string.IsNullOrEmpty(userName))
{

using (var pctx = new PrincipalContext(ContextType.Domain))
{

using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, userName))
{

return up != null && !String.IsNullOrEmpty(up.GivenName) && !String.IsNullOrEmpty(up.Surname) ? string.Format(“{0} {1}”, up.GivenName, up.Surname) : string.Empty;

}

}

}

return string.Empty;

}