C#使用DirectoryEntry類操作Windows帳戶
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
/// <summary> /// 創(chuàng)建Windows帳戶 /// </summary> /// <param name="pathname"></param> /// <returns></returns> public static void CreateLocalUser(string username, string password, string description) { DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); var newUser = localMachine.Children.Add(username, "user"); newUser.Invoke("SetPassword", new object[] { password }); newUser.Invoke("Put", new object[] { "Description", description }); newUser.CommitChanges(); localMachine.Close(); newUser.Close(); } /// <summary> /// 更改Windows帳戶密碼 /// </summary> /// <param name="username"></param> /// <param name="oldPwd"></param> /// <param name="newPwd"></param> public static void ChangeWinUserPasswd(string username, string oldPwd, string newPwd) { DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry user = localMachine.Children.Find(username, "user"); object[] password = new object[] { oldPwd, newPwd }; object ret = user.Invoke("ChangePassword", password); user.CommitChanges(); localMachine.Close(); user.Close(); } /// <summary> /// 判斷Windows用戶是否存在 /// </summary> /// <param name="username"></param> /// <returns></returns> public static bool ExistWinUser(string username) { try { using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer")) { var user = localMachine.Children.Find(username, "user"); return user != null; } } catch { return false; } } /// <summary> /// 刪除Windows用戶 /// </summary> /// <param name="username"></param> /// <returns></returns> public static bool DeleteWinUser(string username) { try { using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer")) { //刪除存在用戶 var delUser = localMachine.Children.Find(username, "user"); if (delUser != null) { localMachine.Children.Remove(delUser); } } return true; } catch { return false; } } /// <summary> /// 啟用/禁用windows帳戶 /// </summary> /// <param name="username"></param> public static void Disable(string username, bool isDisable) { var userDn = "WinNT://" + Environment.MachineName + "/" + username + ",user"; DirectoryEntry user = new DirectoryEntry(userDn); user.InvokeSet("AccountDisabled", isDisable); user.CommitChanges(); user.Close(); } 該文章在 2021/6/26 23:49:24 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |