服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 使用C#实现Windows组和用户管理的示例代码

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

2022-10-26 13:33xhubobo C#

这篇文章主要介绍了使用C#实现Windows组和用户管理的示例代码,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下

1、WindowsAccountHelper类实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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、使用示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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组和用户管理的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/xhubobo/p/13427127.html

延伸 · 阅读

精彩推荐
  • C#C#关于Task.Yeild()函数的讨论

    C#关于Task.Yeild()函数的讨论

    这篇文章主要介绍了C#中关于Task.Yeild()函数的相关资料,文中讲解非常细致,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    白烟染黑墨5352022-09-26
  • C#C#获取本地IP的四种方式示例详解

    C#获取本地IP的四种方式示例详解

    这篇文章主要介绍了C#获取本地IP的四种方式示例详解, 文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    Koalin11322022-09-28
  • C#C# 爬虫简单教程

    C# 爬虫简单教程

    这篇文章主要介绍了C# 爬虫的简单教程,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...

    张缺缺3412022-10-25
  • C#C# Mqtt 断线重连的实现代码

    C# Mqtt 断线重连的实现代码

    这篇文章主要介绍了C# Mqtt 断线重连,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来...

    时间维度3282022-08-04
  • C#C#实现简易猜数字游戏

    C#实现简易猜数字游戏

    这篇文章主要为大家详细介绍了C#实现简易猜数字游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    飘散的枫叶9372022-02-22
  • C#C#中list用法实例

    C#中list用法实例

    这篇文章主要介绍了C#中list用法,结合实例形式分析了C#中list排序、运算、转换等常见操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    smartsmile201210912021-11-26
  • C#深入解析C#编程中泛型委托的使用

    深入解析C#编程中泛型委托的使用

    这篇文章主要介绍了C#编程中泛型委托的使用,引用泛型委托的代码可以指定类型参数以创建已关闭的构造类型,需要的朋友可以参考下...

    Fastyou4312021-11-12
  • C#详解c# 类的构造方法

    详解c# 类的构造方法

    本文主要介绍了c#类的构造方法。具有一定的参考价值,下面跟着小编一起来看下吧...

    liyongke4612021-12-20