I am trying to create new local user accounts on a Windows 7 machine. I used the System.DirectoryServices.DirectoryEntry class (as in here ), but it does not work.
Here is the code in the article:
static void Main(string[] args) { try { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add("TestUser1", "user"); NewUser.Invoke("SetPassword", new object[] {"#12345Abc"}); NewUser.Invoke("Put", new object[] {"Description", "Test User from .NET"}); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Guests", "group"); if (grp != null) {grp.Invoke("Add", new object[] {NewUser.Path.ToString()});} Console.WriteLine("Account Created Successfully"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
When executing this line
DirectoryEntry NewUser = AD.Children.Add("TestUser1", "user");
I get
System.Runtime.InteropServices.COMException with " {"Unknown error (0x80005000)"} "
as an exception message and -2147463168 as an error code.
I guess this is probably because the article is about Windows XP and below machines, and I focus on Windows 7 and Windows Server 2008.
Any help appreciated!
Update:
For some mysterious reason, I no longer see this System.Runtime.InteropServices.COMException , but when making changes here newuser.CommitChanges() I get a " UnAuthorizedAccessException ". I tried to run the application as an administrator, but still did not work.
Update 2:
OK, after switching to the UserPrincipal class, I got the following code:
public UserPrincipal CreateNewUser(string sUserName, string sPassword) {
This code works well when I run it as a console application - of course, it runs as an administrator, but when I deploy it as a Windows service, with a security account set to "LocalSystem", I get an InvlaidOperationException message "The main store does not support this property"
Thoughts?