如何使用 C# 删除 Windows 用户帐户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/642406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove windows user account using C#
提问by
How to remove windows user account using C#?
如何使用 C# 删除 Windows 用户帐户?
回答by Chris Van Opstal
Clause Thomsen was close, you need to pass the DirectoryEntry.Remove method a DirectoryEntry paramenter and not a string, like:
条款 Thomsen 很接近,您需要将 DirectoryEntry.Remove 方法传递给 DirectoryEntry 参数而不是字符串,例如:
DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
DirectoryEntries users = localDirectory.Children;
DirectoryEntry user = users.Find("userName");
users.Remove(user);
回答by Claus Thomsen
Something like this should do the trick(not tested):
这样的事情应该可以解决问题(未测试):
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntries entries = localMachine.Children;
DirectoryEntry user = entries.Remove("User");
entries.CommitChanges();
回答by Claus Thomsen
Alternatively using System.DirectoryServices.AccountManagement in .NET 3.5:-
或者在 .NET 3.5 中使用 System.DirectoryServices.AccountManagement:-
回答by X-Misaya
using System;
using System.DirectoryServices.AccountManagement;
namespace AdministratorsGroupSample
{
class Program
{
static void Main(string[] args)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
GroupPrincipal grpp = new GroupPrincipal(ctx);
UserPrincipal usrp = new UserPrincipal(ctx);
PrincipalSearcher ps_usr = new PrincipalSearcher(usrp);
PrincipalSearchResult<Principal> fr_usr = ps_usr.FindAll();
PrincipalSearcher ps_grp = new PrincipalSearcher(grpp);
PrincipalSearchResult<Principal> fr_grp = ps_grp.FindAll();
foreach (var usr in fr_usr)
{
Console.WriteLine($"Name:{usr.Name} SID:{usr.Sid} Desc:{usr.Description}");
Console.WriteLine("\t Groups:");
foreach (var grp in usr.GetGroups())
{
Console.WriteLine("\t" + $"Name:{grp.Name} SID:{grp.Sid} Desc:{grp.Description}");
}
Console.WriteLine();
}
Console.WriteLine();
foreach (var grp in fr_grp)
{
Console.WriteLine($"{grp.Name} {grp.Description}");
}
Console.ReadLine();
}
private void Delete(string userName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal usrp = new UserPrincipal(ctx);
usrp.Name = userName;
PrincipalSearcher ps_usr = new PrincipalSearcher(usrp);
var user = ps_usr.FindOne();
user.Delete();
}
}
}