Creating local user account c# and .NET 2.0

前端 未结 3 1080
说谎
说谎 2020-12-01 03:28

How can I create a local user account using .NET 2.0 and c# and also be able to set the \"Password never expires\" to never.

I have tried using \"Net.exe\" using Pr

3条回答
  •  渐次进展
    2020-12-01 03:52

    This code will create a local account with the password never expires option set:

            using System.DirectoryServices;
    
            DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
            DirectoryEntries entries = hostMachineDirectory.Children;
            bool userExists = false;
            foreach (DirectoryEntry each in entries)
            {
                userExists = each.Name.Equals("NewUser",  
                StringComparison.CurrentCultureIgnoreCase);
                if (systemtestUserExists)
                    break;
            }
    
            if (false == userExists)
            {
                DirectoryEntry obUser = entries.Add("NewUser", "User");
                obUser.Properties["FullName"].Add("Local user");
                obUser.Invoke("SetPassword", "abcdefg12345@");
                obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
                obUser.CommitChanges();
            }
    

    The 0x10000 flag means PasswordNeverExpires.

    I spent a long time figuring out how to create a local user account with the password set not to expire. It seems that when you try to use:

    int val = (int)newUser.Properties["userAccountControl"].Value; 
    newUser.Properties["userAccountControl"].Value = val | 0x10000
    

    permissions from active directory come into play. If you have active directory permissions everything works fine. If you don't then getting the userAccountControl property will always result in a null value. Trying to set userAccountControl will result in an exception "The directory property cannot be found in the cache".

    However after much hunting around I found another property "UserFlags" that needs to be set using Invoke. You can use this to set the flag on a local account. I've tried this code and it worked on windows server 2008.

    Hope this helps

提交回复
热议问题