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([MarshalAs(UnmanagedType.LPTStr)] string servername, int level, ref USER_INFO_1 buf, int parm_err);
[DllImport("Netapi32.dll")]
extern static int NetLocalGroupAdd([MarshalAs(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
{
[MarshalAs(UnmanagedType.LPWStr)]public string Add_localgroup_1_name;
[MarshalAs(UnmanagedType.LPWStr)]public string Add_localgroup_1_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_1_comment = "Add a User to the Administrators Group";
if (NetLocalGroupAdd(null, 1, ref AddToGroup , 0) != 0)
{
Console.Write("Adding To the Administrators Group Failed");
}
}
}
}
发表于 @ 2008年01月28日 22:02:00|评论(loading...)|编辑