The example above does have some issues; especially with its handling of null values in the DirectoryEntry object. I used the sAMAccountName and have posted by code below:
try
{
// Get the user name of the current user.
string userName = this.Application.User.UserName;
// Create a DirectorySearcher object using the user name
// as the LDAP search filter. If using a directory other
// than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher(
"(sAMAccountName=" + userName + ")");
// Search for the specified user.
SearchResult result = searcher.FindOne();
// Make sure the user was found.
if (result == null)
{
MessageBox.Show("Error finding user: " + userName);
}
else
{
// Create a DirectoryEntry object to retrieve the collection
// of attributes (properties) for the user.
DirectoryEntry employee = result.GetDirectoryEntry();
// Assign the specified properties to string variables.
string FirstName = employee.Properties["givenName"].Value.ToString();
string LastName = employee.Properties["sn"].Value.ToString();
string Mail = employee.Properties["mail"].Value.ToString();
string Location = string.Empty;
if (employee.Properties["physicalDeliveryOfficeName"].Value != null)
{
Location = employee.Properties["physicalDeliveryOfficeName"].Value.ToString();
}
string Title = string.Empty;
if (employee.Properties["title"].Value != null)
{
Title =employee.Properties["title"].Value.ToString();
}
string Phone = string.Empty;
if(employee.Properties["telephoneNumber"].Value != null)
{
Phone =employee.Properties["telephoneNumber"].Value.ToString();
}
string Department = string.Empty;
if(employee.Properties["department"].Value != null)
{
Department =employee.Properties["department"].Value.ToString();
}
// The manager property returns a distinguished name,
// so get the substring of the common name following "CN=".
string ManagerName = string.Empty;
if (employee.Properties["manager"].Value != null)
{
ManagerName = employee.Properties["manager"].Value.ToString();
ManagerName = ManagerName.Substring(
3, ManagerName.IndexOf(",") - 3);
}
//the rest is the same...
}
catch (Exception ex)
{
MessageBox.Show("The following error occurred: " + ex.Message.ToString());
throw;
}