如何使用C#删除Windows用户帐户

5lwkijsr  于 2023-10-22  发布在  Windows
关注(0)|答案(4)|浏览(127)

如何使用C#删除Windows用户帐户?

vhmi4jdf

vhmi4jdf1#

Clause Thomsen很接近,你需要给DirectoryEntry.Remove方法传递一个DirectoryEntry参数,而不是一个字符串,比如:

DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
DirectoryEntries users = localDirectory.Children;
DirectoryEntry user = users.Find("userName");
users.Remove(user);
mi7gmzs6

mi7gmzs62#

类似这样的东西应该可以做到这一点(未经测试):

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" +  Environment.MachineName);

DirectoryEntries entries = localMachine.Children;
DirectoryEntry user = entries.Remove("User");
entries.CommitChanges();
fxnxkyjh

fxnxkyjh3#

或者在.NET 3.5中使用System.DirectoryServices.AccountManagement:
http://msdn.microsoft.com/en-us/library/bb924557.aspx

htrmnn0y

htrmnn0y4#

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();
        }
    }
}

相关问题