Hi,
a short post. It describes how to create a new local Windows User account and add them to an existing local user group.
First of all, include the following references in your project:
1 2 | using System.DirectoryServices;using System.Runtime.InteropServices; |
Create a new User with local administrator rights.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // define Username and Passwordconst string USER_NAME = "NewAdmin";char[] aPWchars = { 'P', 'a', 's', 's' , 'w', 'o', 'r', 'd'};System.Security.SecureString oPW = new System.Security.SecureString();foreach (char cChr in aPWchars) { oPW.AppendChar(cChr);}// Get Computerobject via ADSIDirectoryEntry oComputer = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");// New UserDirectoryEntry oNewUser = oComputer.Children.Add(USER_NAME, "user");// define Pointer to a stringIntPtr pString = IntPtr.Zero;// Pointer to passwordpString = Marshal.SecureStringToGlobalAllocUnicode(oPW);// Set passwordoNewUser.Invoke("SetPassword", new object[] { Marshal.PtrToStringUni(pString) });// Add a descriptionoNewUser.Invoke("Put", new object[] { "Description", "New Administrator" });// Save changesoNewUser.CommitChanges();// Cleanup and free Password pointerMarshal.ZeroFreeGlobalAllocUnicode(pString);// Get GroupDirectoryEntry oGroup = oComputer.Children.Find("Administrators", "group");// And add the recently created useroGroup.Invoke("Add", new object[] { oNewUser.Path.ToString() }); |
Michael
This doesn’t provide any security at all… As soon as you call Marshal.PtrToStringUni(pString) you create a common .NET String instance which can’t be garbage collected anymore. This example provides just an illusion of security whichs is actually more dangerous than using a normal String.
Hi Michael. This snipped should just demonstrate how to add an administrator. Defining a hardcoded password is never a good idea but this let you copy the example in your project which then can be altered to your needs. Do you have a better way to set the password in program?