日期:2014-05-18  浏览次数:21120 次

C#在远程计算机上创建新用户账号,修改用户密码,删除一个用户账号的功能?
1.为了实现标题上的功能,搜索了一阵只是找到了如下的wmi代码,虽然可以实现想要的功能,但无法准确判断是否成功创建,删除用户账号或者成功修改了用户密码。(net.exe 只是可以知道命令是不是执行了即使出错没修改成功,也不错报错,出错只是在命令行上输出)
2.利用DirectoryEntry不知道可不可以实现远程添加、删除用户账号或者密码的功能。
3.第三种是利用win32 api提供的功能来实现的相应的功能,net中还要使用win32 api吗?
Public Declare Function NetUserAdd Lib "netapi32" (lpServer As Any, ByVal Level As Long, lpUser As USER_INFO_3_API, lpError As Long) As Long
Public Declare Function NetUserChangePassword Lib "Netapi32.dll" (Domain As Any, User As Any, OldPass As Byte, NewPass As Byte) As Long
Declare Function NetUserDel Lib "netapi32.dll" (ServerName As Byte, Username As Byte) As Long
------------------
DirectoryEntry de=new DirectoryEntry("WinNT://<计算机名>/guest" yourID,yourPWD);  
   
  int v=de.Properties["userAccountControl"].value;  
   
  de.Properties["userAccountControl"].value=2&~v;  
   
  de.CommitChanges();  

------------------------------
  WMI远程添加修改用户 
  /// <summary>
  /// WMI用户操作
  /// </summary>
  public class Win32_UserAccount
  {
  private string ip = string.Empty;
  public string IP
  {
  get { return ip; }
  set { ip = value; }
  }

  private string username = string.Empty;
  public string UserName
  {
  get { return username; }
  set { username = value; }
  }

  private string password;

  public string PassWord
  {
  get { return password; }
  set { password = value; }
  }

  /// <summary>
  /// 构造函数
  /// </summary>
  /// <param name="_ip">目标IP地址</param>
  /// <param name="_username">管理员用户名</param>
  /// <param name="_password">密码</param>
  public Win32_UserAccount(string _ip, string _username, string _password)
  {
  IP = _ip;
  UserName = _username;
  PassWord = _password;
  } 

  /// <summary>
  /// 返回所有用户
  /// </summary>
  /// <returns>帐号数组</returns>
  public string[] ViweUsers()
  {
  try
  {
  ConnectionOptions options = new ConnectionOptions();
  options.Username = UserName;
  options.Password = PassWord;

  ManagementScope Conn = new ManagementScope(@"\\" + IP + @"\root\cimv2", options);
  Conn.Connect();
  //确定WMI操作的内容
  ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_UserAccount");
  ManagementObjectSearcher query1 = new ManagementObjectSearcher(Conn, oq);
  //获取WMI操作内容
  ManagementObjectCollection queryCollection1 = query1.Get();
  //根据使用者选择,执行相应的远程操作
  string[] s = new string[queryCollection1.Count];
  int i=0;
  foreach (ManagementObject mo in queryCollection1)
  {
  s[i] +=