Reputation: 8452
When using DirectoryEntry
, it is possible to set the CN of the new user account, but how to do it using UserPrincipal
? The property is readonly.
// From : http://msdn.microsoft.com/en-us/magazine/cc135979.aspx
DirectoryEntry container = new DirectoryEntry("LDAP://ou=TechWriters,dc=fabrikam,dc=com");
// create a user directory entry in the container
DirectoryEntry newUser = container.Children.Add("cn=user1Acct", "user");
// add the samAccountName mandatory attribute
newUser.Properties["sAMAccountName"].Value = "User1Acct";
// save to the directory
newUser.CommitChanges();
But using UserPrincipal:
// For the example
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "ou=TechWriters,dc=fabrikam,dc=com")
{
using (UserPrincipal user = new UserPrincipal(ctx, "User1Acct", "pwd", true))
{
// I would like to do :
user.DistinguishedName = "user1Acct";
//
user.Save();
}
}
Upvotes: 3
Views: 3191
Reputation: 2877
Not the answer you want, but to my knowledge its not doable that way... The CN is 'protected' om the userprinciple class, as too much elsewhere relies on that being stable information.
I don't know why one would mix things up, but you could try this:
using (var ctx = new PrincipalContext(ContextType.Domain, null, "ou=TechWriters,dc=fabrikam,dc=com"))
{
using (var user = new UserPrincipal(ctx, "User1Acct", "pwd", true))
{
user.Save();
}
using (var entry = new DirectoryEntry("LDAP://cn=User1Acct;ou=TechWriters,dc=fabrikam,dc=com",null,null,AuthenticationTypes.Secure))
{
entry.Rename("cn=user1Acct");
}
}
(Maybe getting the LDAP string from the userPrinciple instead of hardcoding)
I do not have the possibillity to test this though..
Upvotes: 4