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.
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, netapi32.lib)
#include <stdio.h>
#include <windows.h>
#include <lm.h>
int wmain(int argc, wchar_t *argv[])
{
USER_INFO_1 ui;
DWORD dwLevel = 1;
DWORD dwError = 0;
NET_API_STATUS nStatus;
if (argc != 3)
{
fwprintf_s(stderr, LUsage: %s \\\\ServerName UserName\n, argv[0]);
wprintf(LExample: %s \\\\MikeServer Smith\n, argv[0]);
exit(1);
}
// 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[2];
ui.usri1_password = argv[2];
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[1],dwLevel,(LPBYTE)&ui,&dwError);
// If the call succeeds, inform the user.
if (nStatus == NERR_Success)
{
wprintf(LNetUserAdd() is OK!\n);
fwprintf_s(stderr, LUser %s has been successfully added on %s\n,argv[2], argv[1]);
}
// Otherwise, print the system error.
else
{
wprintf(LNetUserAdd() failed!\n);
fwprintf_s(stderr, LA system error has occurred: %d\n, nStatus);
}
return 0;
}
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.