Using Win32 API netuseradd and netlocalgroupadd to add a user account in Administrators Group
By delphiscn (Delphiscn@gmail.com) http://blog.csdn.net/delphiscn
Environment: Windows Vista Home Premium VS 2005 NET 2.0
Using system. runtime. interopservices;
Using Microsoft. Win32;
Using system;
Namespace task
{
Class adduserapplication
{
[Dllimport ("netapi32.dll")]
Extern static int netuseradd ([financialas (unmanagedtype. lptstr)] string servername, int level, ref user_info_1 Buf, int parm_err );
[Dllimport ("netapi32.dll")]
Extern static int netlocalgroupadd ([financialas (unmanagedtype. lptstr)] string servername, int level, ref localgroup_info_1 Buf, int parm_err );
[Structlayout (layoutkind. Sequential, charset = charset. Unicode)]
Public struct user_info_1
{
Public String user_information_1_name;
Public String user_information_1_password;
Public String user_information_1_password_age;
Public int user_information_1_priv;
Public String user_information_1_home_dir;
Public String comment;
Public int user_information_1_flags;
Public String user_information_1_script_path;
}
Public struct localgroup_info_1
{
[Financialas (unmanagedtype. lpwstr)] Public String add_localgroup_1_name;
[Financialas (unmanagedtype. lpwstr)] Public String add_localgroup_comment comment;
}
Public static void main ()
{
If (add_a_user_account () = false)
{
Console. Write ("error: Adding User Failed sorry ");
}
Else
Add_a_useraccount_to_localgroup ();
}
// Public static void usage ()
//{
// Console. Write ("------------------------------------");
// Console. Write ("code by delphiscn 2008-01-28 ");
// Console. Write ("Email: Delphiscn@gmail.com ");
// Console. Write ("blog: [url] http://blog.csdn.net/delphiscn#/url]");
// Console. Write ("------------------------------------");
//}
Public static Boolean add_a_user_account ()
{
User_info_1 adduser = new user_info_1 ();
Adduser. user_information_1_name = "delphiscn ";
Adduser. user_information_1_password = "eviloctal ";
Adduser. user_information_1_priv = 1;
Adduser. user_information_1_home_dir = NULL;
Adduser. Comment = "add a user named delphiscn ";
Adduser. user_information_1_script_path = NULL;
If (netuseradd (null, 1, ref adduser, 0 )! = 0)
{
Console. Write ("error: Adding User Failed ");
Return false;
}
Return true;
}
Public static void add_a_useraccount_to_localgroup ()
{
Localgroup_info_1 addtogroup = new localgroup_info_1 ();
Addtogroup. add_localgroup_1_name = "Administrators ";
Addtogroup. add_localgroup_comment comment = "add a user to the Administrators group ";
If (netlocalgroupadd (null, 1, ref addtogroup, 0 )! = 0)
{
Console. Write ("adding to the Administrators group failed ");
}
}
}
}