Mark
Mark

Reputation:

How to remove windows user account using C#

How to remove windows user account using C#?

Upvotes: 14

Views: 10399

Answers (4)

Chris Van Opstal
Chris Van Opstal

Reputation: 37547

Clause Thomsen was close, you need to pass the DirectoryEntry.Remove method a DirectoryEntry parameter instead of a string, like:

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

Upvotes: 12

X-Misaya
X-Misaya

Reputation: 171

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

Upvotes: -1

nom
nom

Reputation:

Alternatively using System.DirectoryServices.AccountManagement in .NET 3.5:-

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

Upvotes: 0

Claus Thomsen
Claus Thomsen

Reputation: 2355

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

Upvotes: 3

Related Questions