Read, Add, Delete Windows users in .NET

2019-07-20 15:37发布

问题:

I want to Read, Add and Delete users from a Windows using .NET code. How can I do that?

回答1:

Here's some sample code for creating a windows user:

public static bool CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
{
    try
    {
        PrincipalContext context = new PrincipalContext(ContextType.Machine);
        UserPrincipal user = new UserPrincipal(context);
        user.SetPassword(password);
        user.DisplayName = displayName;
        user.Name = username;
        user.Description = description;
        user.UserCannotChangePassword = canChangePwd;
        user.PasswordNeverExpires = pwdExpires;
        user.Save();

        //now add user to "Users" group so it displays in Control Panel
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users");
        group.Members.Add(user);
        group.Save();

        return true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error creating account: {0}", ex.Message);
        return false;
    }

}

Adding a reference to System.DirectoryServices will let you read all windows users doing something like this:

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators", "group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
    DirectoryEntry member = new DirectoryEntry(groupMember);
    lstUsers.Items.Add(member.Name);
}

The DirectoryServices Namespace in general should let you navigate and read the Active Directory



回答2:

You will want to use the ActiveDirectory and DirectoryEntry

Imports System.DirectoryServices.ActiveDirectory
Imports System.Collections.DictionaryEntry

LDAP is one option I would think WinNT would works as well.

You can access the directory with WinNT:// like this

    Dim de As New System.DirectoryServices.DirectoryEntry()  
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs Handles Button1.Click      
     de.Path = "WinNT://*****".Replace("*****", ActiveDirectory.DomainGetCurrentDomain.Name)    

Here are a few helpful links that have examples for adding/removing etc

Working with Users

SO Remove User

Also I had a few questions involving ActiveDirectory use a month or so ago (so I don't remember them in depth). Maybe some stuff from my profile can help you out. Good Luck



回答3:

Apart from the other answers which are definitely valid and good we have also used LINQ to AD...

http://linqtoad.codeplex.com/

...on some projects which can make simple querying quite easy.



标签: .net windows add