使用C#实现Windows组和用户管理的示例代码

转载 https://blog.csdn.net/chinaherolts2008/article/details/115312687

using System.DirectoryService.AccontManagement
public class WinAccountHelper
    {
        public static string LastErrorMsg { get; set; }

        public static List<string> GetGroups()
        {
            var groups = new List<string>();
            try
            {
                var context = new PrincipalContext(ContextType.Machine);
                var queryGroup = new GroupPrincipal(context);
                var searcher = new PrincipalSearcher(queryGroup);
                searcher.FindAll().ToList().ForEach(t => groups.Add(t.Name));
            }
            catch (Exception)
            {
                groups.Clear();
            }

            return groups;
        }

        public static List<string> GetGroupUsers(string groupName)
        {
            var group = GetGroup(groupName);
            return GetGroupUsers(group);
        }

        public static List<string> GetGroupUsers(GroupPrincipal group)
        {
            var users = new List<string>();

            if (group == null)
            {
                return users;
            }

            group.GetMembers().ToList().ForEach(t => users.Add(t.Name));
            return users;
        }

        public static GroupPrincipal GetGroup(string groupName)
        {
            GroupPrincipal group = null;
            try
            {
                var context = new PrincipalContext(ContextType.Machine);
                var queryGroup = new GroupPrincipal(context);
                var searcher = new PrincipalSearcher(queryGroup);
                foreach (var principal in searcher.FindAll())
                {
                    var groupPrincipal = (GroupPrincipal)principal;
                    if (groupPrincipal != null && groupPrincipal.Name.Equals(groupName))
                    {
                        group = groupPrincipal;
                        break;
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return group;
        }

        public static GroupPrincipal CreateGroup(string groupName, string description, bool isSecurityGroup)
        {
            GroupPrincipal group;
            try
            {
                group = GetGroup(groupName);
                if (group == null)
                {
                    var context = new PrincipalContext(ContextType.Machine);
                    group = new GroupPrincipal(context)
                    {
                        Name = groupName,
                        Description = description,
                        IsSecurityGroup = isSecurityGroup,
                        GroupScope = GroupScope.Local
                    };
                    group.Save();
                }
            }
            catch (Exception e)
            {
                LastErrorMsg = e.Message;
                group = null;
            }

            return group;
        }

        public static bool DeleteGroup(string groupName)
        {
            var group = GetGroup(groupName);
            if (group == null)
            {
                return true;
            }

            var ret = true;
            try
            {
                group.Delete();
            }
            catch (Exception)
            {
                ret = false;
            }

            return ret;
        }

        public static bool CreateWindowsAccount(string userName, string password,
            string displayName, string description, bool cannotChangePassword,
            bool passwordNeverExpires, string groupName)
        {
            bool ret;
            try
            {
                var context = new PrincipalContext(ContextType.Machine);
                var group = GroupPrincipal.FindByIdentity(context, groupName);
                if (group == null)
                {
                    return false;
                }

                ret = CreateWindowsAccount(userName, password, displayName,
                    description, cannotChangePassword, passwordNeverExpires, group);
            }
            catch (Exception)
            {
                ret = false;
            }

            return ret;
        }

        public static bool CreateWindowsAccount(string userName, string password,
            string displayName, string description, bool cannotChangePassword,
            bool passwordNeverExpires, GroupPrincipal group)
        {
            bool ret;
            try
            {
                if (group == null)
                {
                    return false;
                }

                var context = new PrincipalContext(ContextType.Machine);
                var user = UserPrincipal.FindByIdentity(context, userName)
                           ?? new UserPrincipal(context);
                user.SetPassword(password);
                user.DisplayName = displayName;
                user.Name = userName;
                user.Description = description;
                user.UserCannotChangePassword = cannotChangePassword;
                user.PasswordNeverExpires = passwordNeverExpires;
                user.Save();

                group.Members.Add(user);
                group.Save();
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }

            return ret;
        }

        public static bool DeleteWindowsAccount(List<string> userNameList)
        {
            var ret = true;
            try
            {
                foreach (var userName in userNameList)
                {
                    var context = new PrincipalContext(ContextType.Machine);
                    var user = UserPrincipal.FindByIdentity(context, userName);
                    user?.Delete();
                }
            }
            catch (Exception)
            {
                ret = false;
            }

            return ret;
        }

        public static bool ChangeUserGroup(string userName, string groupName)
        {
            bool ret;
            try
            {
                var context = new PrincipalContext(ContextType.Machine);
                var group = GroupPrincipal.FindByIdentity(context, groupName);
                if (group == null)
                {
                    return false;
                }

                ret = ChangeUserGroup(userName, group);
            }
            catch (Exception)
            {
                ret = false;
            }

            return ret;
        }

        public static bool ChangeUserGroup(string userName, GroupPrincipal group)
        {
            bool ret;
            try
            {
                if (group == null)
                {
                    return false;
                }

                var context = new PrincipalContext(ContextType.Machine);
                var user = UserPrincipal.FindByIdentity(context, userName);
                if (user == null)
                {
                    return false;
                }

                if (!group.Members.Contains(user))
                {
                    group.Members.Add(user);
                    group.Save();
                }

                ret = true;
            }
            catch (Exception)
            {
                ret = false;
            }

            return ret;
        }

        public static int UpdateGroupUsers(string groupName, List<string> userNames, string password = "")
        {
            var group = CreateGroup(groupName, string.Empty, false);
            if (group == null)
            {
                return 0;
            }

            var userNameList = new List<string>();
            userNameList.AddRange(userNames);

            var addedUsers = new List<string>();
            int groupUserCount;

            try
            {
                foreach (var principal in group.GetMembers())
                {
                    var user = (UserPrincipal)principal;
                    if (user == null)
                    {
                        continue;
                    }

                    if (userNameList.Contains(user.Name))
                    {
                        //已有用户
                        addedUsers.Add(user.Name);
                    }
                    else
                    {
                        user.Delete();
                    }
                }

                //已有用户数
                groupUserCount = addedUsers.Count;

                //剩余的即为需要添加的用户集合
                foreach (var userName in addedUsers)
                {
                    userNameList.Remove(userName);
                }

                //创建用户
                foreach (var userName in userNameList)
                {
                    if (CreateWindowsAccount(userName, password,
                        userName, string.Empty,
                        false, false, group))
                    {
                        groupUserCount++;
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                groupUserCount = 0;
            }

            return groupUserCount;
        }

        public bool CreateGroupUsers(string groupName, List<string> windowsUserList, string password, int userCount)
        {
            var group = CreateGroup(groupName, string.Empty, true);
            if (group == null)
            {
                return false;
            }

            var userNames = GetGroupUsers(group);
            foreach (var userName in windowsUserList)
            {
                if (!userNames.Contains(userName))
                {
                    if (!CreateWindowsAccount(userName, password,
                        userName, string.Empty,
                        false, false, group))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值