Introduction
Here, we are going to learn to make Windows local user account using C#. We will make a C# console application and write the code in it to create user accounts via C#.
Tools
You just need Visual Studio installed on your PC to start working.
Targeted Audience
People with basic knowledge of C# are the targeted audience.
Note
You need to run Visual Studio as an administrator in order to get permission and to create Local Windows account.
What you need to do?
Checklist
- Run Visual Studio as administrator.
- Make a C# console application and select your targeting .NET framework.
- Add the reference “System.DirectoryServices ” in your project.
- Code and Run
Firstly, make a C# console application, and then, add the reference given blow to start development.
Here is the reference you need to add.
Code
Code for main Program.cs file.
- class Program
- {
- public static string Name;
- public static string Pass;
-
-
- static void Main(string[] args)
- {
- Console.WriteLine("Windows Account Creator");
- Console.WriteLine("Enter User Name");
- Name = Console.ReadLine();
-
- Console.WriteLine("Enter User Password");
- Pass = Console.ReadLine();
-
- createUser(Name, Pass);
-
- }
-
- public static void createUser(string Name, string Pass) {
-
-
- try
- {
- DirectoryEntry AD = new DirectoryEntry("WinNT://" +
- Environment.MachineName + ",computer");
- DirectoryEntry NewUser = AD.Children.Add(Name, "user");
- NewUser.Invoke("SetPassword", new object[] { Pass });
- NewUser.Invoke("Put", new object[] { "Description", "Test User from .NET" });
- NewUser.CommitChanges();
- DirectoryEntry grp;
-
- grp = AD.Children.Find("Administrators", "group");
- if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
- Console.WriteLine("Account Created Successfully");
- Console.WriteLine("Press Enter to continue....");
- Console.ReadLine();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.ReadLine();
-
- }
-
- }
- }
By this code, you can add user account in administrator group. If you need to add a Guest User. You can change “Administrators” to “Guest”.
Output
This is the output of our console application.
Here, you see that a new local Windows account is created with the username “New User” in administrator group.