C#使用DirectoryEntry类操作Windows帐户
引用 http://www.cnblogs.com/skynothing/archive/2010/07/26/1785344.html
这几天使用C#操作windows帐户相当纠结,以前没做过,google翻阅了不少资料,尝试不少方法,终于解决了我的问题。
1.创建windows帐户
view sourceprint?01 /// <summary>
02 /// 创建Windows帐户
03 /// </summary>
04 /// <param name="pathname"></param>
05 /// <returns></returns>
06 public static void CreateLocalUser(string username, string password, string description)
07 {
08 DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
09 var newUser = localMachine.Children.Add(username, "user");
10 newUser.Invoke("SetPassword", new object[] { password });
11 newUser.Invoke("Put", new object[] { "Description", description });
12 newUser.CommitChanges();
13 localMachine.Close();
14 newUser.Close();
15 }
2.更改Windows帐户密码
view sourceprint?01 /// <summary>
02 /// 更改Windows帐户密码
03 /// </summary>
04 /// <param name="username"></param>
05 /// <param name="oldPwd"></param>
06 /// <param name="newPwd"></param>
07 public static void ChangeWinUserPasswd(string username, string oldPwd, string newPwd)
08 {
09 DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
10 DirectoryEntry user = localMachine.Children.Find(username, "user");
11 object[] password = new object[] { oldPwd, newPwd };
12 object ret = user.Invoke("ChangePassword", password);
13 user.CommitChanges();
14 localMachine.Close();
15 user.Close();
16 }
3.判断Windows用户是否存在
view sourceprint?01 /// <summary>
02 /// 判断Windows用户是否存在
03 /// </summary>
04 /// <param name="username"></param>
05 /// <returns></returns>
06 public static bool ExistWinUser(string username)
07 {
08 try
09 {
10 using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
11 {
12 var user = localMachine.Children.Find(username, "user");
13 return user != null;
14 }
15 }
16 catch
17 {
18 return false;
19 }
20 }
4.删除Windows用户view sourceprint?01 /// <summary>
02 /// 删除Windows用户
03 /// </summary>
04 /// <param name="username"></para