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

1、WindowsAccountHelper类实现

using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
 
public class WindowsAccountHelper
{
    public static string LastErrorMsg { get; private 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)
        {
            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;
    }
}

2、使用示例

private bool CreateGroupUsers(string groupName, List<string> windowsUserList,
    string password, int userCount)
{
    var group = WindowsAccountHelper.CreateGroup(groupName, string.Empty, true);
    if (group == null)
    {
        return false;
    }
 
    var userNames = WindowsAccountHelper.GetGroupUsers(group);
    foreach (var userName in WindowsUserList)
    {
        if (!userNames.Contains(userName))
        {
            if (!WindowsAccountHelper.CreateWindowsAccount(userName, password,
                userName, string.Empty,
                false, false, group))
            {
                return false;
            }
        }
    }
 
    return true;
}

以上就是使用C#实现Windows组和用户管理的示例代码的详细内容,更多关于C#实现Windows组和用户管理的资料请关注我们其它相关文章!

(0)

相关推荐

  • 使用C#创建Windows服务的实例代码

    本文介绍了使用C#创建Windows服务的实例代码,分享给大家 一.开发环境 操作系统:Windows 10 X64 开发环境:VS2015 编程语言:C# .NET版本:.NET Framework 4.0 目标平台:X86 二.创建Windows Service 1.新建一个Windows Service,并将项目名称改为"MyWindowsService",如下图所示: 2.在解决方案资源管理器内将Service1.cs改为MyService1.cs后并点击"查看代码&

  • C# 屏蔽由于崩溃弹出的windows异常弹框

    windows应用程序(包括控制台)在运行时如果出现了未处理的异常会出项windows的异常提示框 这个提示框在平时并没有什么影响.但是当我们使用启动的是一个服务器程序时,我们的要求应该是尽可能快的重启应用. 但是由于这个提示框导致我们的第三方守护程序并不知道应用已经崩溃退出,导致我们无法及时处理. 所以,我们应该在程序启动时再做一个处理,即添加未处理异常的事件 C#:   AppDomain.CurrentDomain.UnhandledException 解释: 此事件提供通知未捕获的异常.

  • C#编写Windows服务程序详细步骤详解(图文)

    一.创建一个Windows Service 1)创建Windows Service项目 2)对Service重命名 将Service1重命名为你服务名称,这里我们命名为ServiceTest. 二.创建服务安装程序 1)添加安装程序 之后我们可以看到上图,自动为我们创建了ProjectInstaller.cs以及2个安装的组件. 2)修改安装服务名 右键serviceInsraller1,选择属性,将ServiceName的值改为ServiceTest. 3)修改安装权限 右键servicePr

  • C#实现判断当前操作用户管理角色的方法

    本文实例讲述了C#实现判断当前操作用户管理角色的方法.分享给大家供大家参考.具体实现方法如下: /// <summary> /// 判断当前操作用户的管理角色 /// </summary> public static void GetCurrentUserRole() { AppDomain appDomain = System.Threading.Thread.GetDomain(); appDomain.SetPrincipalPolicy(System.Security.Pr

  • C#对Windows服务组的启动与停止操作

    Windows服务大家都不陌生,Windows服务组的概念,貌似MS并没有这个说法. 作为一名软件开发者,我们的机器上安装有各种开发工具,伴随着各种相关服务. Visual Studio可以不打开,SqlServer Management Studio可以不打开,但是SqlServer服务却默认开启了.下班后,我的计算机想用于生活.娱乐,不需要数据库服务这些东西,尤其是在安装了Oracle数据库后,我感觉机器吃力的很. 每次开机后去依次关闭服务,或者设置手动开启模式,每次工作使用时依次去开启服务

  • C#实现的WINDOWS登录功能示例

    本文实例讲述了C#实现的WINDOWS登录功能.分享给大家供大家参考,具体如下: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.Web

  • C#用Topshelf创建Windows服务的步骤分享

    一.项目创建 创建一个控制台应用程序,项目右键->管理 NuGet 程序包->Topshelft及Topshelf.Log4Net. 二.Topshelf配置 一般来说,服务都会设置每隔多长时间执行一次任务,这里使用System.Threading.Timer来做个简单的日志记录,将日志写入到Debug\Log文件夹下.     2.1.Log4Net配置 新建一个log4net.config的配置文件,在其属性的复制到输出目录项下选择始终复制. <?xml version="

  • C# WindowsForm程序同时启动多个窗口类

    C# WindowsForm程序同时启动多个窗口类,具体内容如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MVCProject { /// <summary> /// 多窗口同时启动类 /// <remarks>继承A

  • C#开发windows服务实现自动从FTP服务器下载文件

    最近在做一个每天定点从FTP自动下载节目.xml并更新到数据库的功能.首先想到用 FileSystemWatcher来监控下载到某个目录中的文件是否发生改变,如果改变就执行相应的操作,然后用timer来设置隔多长时间来下载.后来又想想,用windwos服务来实现. 效果图: 执行的Log日志: INFO-2016/5/24 0:30:07--日志内容为:0/30/7进行time触发 INFO-2016/5/24 1:30:07--日志内容为:1/30/7进行time触发 INFO-2016/5/

  • c# 将Minio.exe注册成windows服务

    minio 注册成windows 服务的工具开发 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Management.Automation; using Sys

随机推荐