NetUserAdd() Program Example
The NetUserAdd() function adds a user account and assigns a password and privilege level. User account names are limited to 20 characters and group names are limited to 256 characters. In addition, account names cannot be terminated by a period and they cannot include commas or any of the following printable characters: ", /, \, [, ], :, |, <, >, +, =, ;, ?, *. Names also cannot include characters in the range 1-31, which are nonprintable. The following code sample demonstrates how to add a user account and assign a privilege level using a call to the NetUserAdd() function. The code sample fills in the members of the USER_INFO_1 structure and calls NetUserAdd(), specifying information level 1.
Create a new empty Win32 console application project. Give the project name and change the project location is needed.
Then, add the source file and give it a suitable name.
Then, add the following source code.
#pragma comment(lib, "netapi32.lib")
int wmain(int argc, wchar_t *argv)
DWORD dwLevel = 1;
DWORD dwError = 0;
if (argc != 3)
fwprintf_s(stderr, L"Usage: %s \\\\ServerName UserName\n", argv);
wprintf(L"Example: %s \\\\MikeServer Smith\n", argv);
// Set up the USER_INFO_1 structure.
// USER_PRIV_USER: name identifies a user,
// rather than an administrator or a guest.
// UF_SCRIPT: required
ui.usri1_name = argv;
ui.usri1_password = argv;
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
// Call the NetUserAdd() function, specifying level 1.
nStatus = NetUserAdd(argv,dwLevel,(LPBYTE)&ui,&dwError);
// If the call succeeds, inform the user.
if (nStatus == NERR_Success)
wprintf(L"NetUserAdd() is OK!\n");
fwprintf_s(stderr, L"User %s has been successfully added on %s\n",argv, argv);
// Otherwise, print the system error.
fwprintf_s(stderr, L"A system error has occurred: %d\n", nStatus);
We would like to add a new user, Mike Tyson.
Build and run the project. The following screenshot is a sample output.
Then verify the action. User Mike Tyson should be added as shown in the following screenshot.