The Active Directory attributes need to be addressed by their LDAP names - not what you see in the GUI....
So try this:
using (DirectoryEntry dirEntry = new DirectoryEntry(ldapPath))
{
if (dirEntry.SchemaEntry.Name == "container")
{
using (DirectoryEntry newUser = dirEntry.Children.Add("CN=" + username, "User"))
{
fullname = fname + " " + lname;
newUser.Properties["sAMAccountName"].Value = username;
newUser.Properties["givenName"].Value = fname; // first name
newUser.Properties["sn"].Value = lname; // surname = last name
newUser.Properties["displayName"].Value = fullname;
newUser.Properties["password"].Value = password;
newUser.CommitChanges();
}
}
}
You can find a great Excel spreadsheet showing the names used in the interactive GUI, and what LDAP names they map to, on Richard Mueller's web site here (check out the "Spreadsheet of all Active Directory attributes" and "Spreadsheet of User Properties in Active Directory Users & Computers MMC.")
Or if you're using .NET 3.5 or newer, you could also investigate the new System.DirectoryServices.AccountManagement namespace, which allows you to use nicely shaped objects to handle common tasks.
Your code would look something like this:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, NULL, ldapPath)
{
// create a user principal object
UserPrincipal user = new UserPrincipal(ctx, username, password, true);
// assign some properties to the user principal
user.GivenName = fname;
user.Surname = lname;
user.DisplayName = fullname;
// save the user to the directory
user.Save();
}
Note: the ldapPath should be the container's LDAP path - without any prefixes, e.g. something like CN=Users,DC=YourCompany,DC=com - no LDAP:// or other prefixes.
The plus side is: the UserPrincipal object class already contains nice, strongly-typed and more intuitive properties to handle many of the basic tasks, like creating a new user and setting some of its properties.