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

时间:2009-03-13 12:17:38

标签: c# windows

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

4 个答案:

答案 0 :(得分:12)

条款Thomsen很接近,您需要将DirectoryEntry.Remove方法传递给DirectoryEntry参数而不是字符串,例如:

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

答案 1 :(得分:3)

这样的事情应该成功(未经测试):

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

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

答案 2 :(得分:0)

或者在.NET 3.5中使用System.DirectoryServices.AccountManagement: -

http://msdn.microsoft.com/en-us/library/bb924557.aspx

答案 3 :(得分:-1)

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