我想读,从Windows添加和删除用户使用.NET code。我该怎么办呢?
I want to Read, Add and Delete users from a Windows using .NET code. How can I do that?
下面是一些示例$ C $下创建一个Windows用户:
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;
}
}
添加引用System.DirectoryServices中都会让你阅读所有的Windows用户做这样的事情:
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);
}
借助的DirectoryServices命名空间一般应该让你浏览和阅读活动目录
The DirectoryServices Namespace in general should let you navigate and read the Active Directory