我正在尝试创建一个库来帮助我操作来自Windows Server的Active Directory的信息。
到目前为止,我已成功从Active Directory列表中获取了一组用户。
namespace SharpDirectory
{
public class UserSearcher
{
private List<User> _users;
public string ConnectionString { get; set; }
public string Username { get; set; }
public string Password { get; set; }
/// <summary>
/// Provides a method of accessing user information from Active Directory.
/// </summary>
/// <param name="connectionString">A standard LDAP conncetion string to your active directory server.</param>
/// <param name="username">User that has sufficient permission level to query Active Directory.</param>
/// <param name="password">Password for the entered user.</param>
public UserSearcher(string connectionString, string username, string password)
{
ConnectionString = connectionString;
Username = username;
Password = password;
}
/// <summary>
/// Find all users in an Active Directory.
/// </summary>
/// <returns>A List of User objects.</returns>
public List<User> FindAllUsers()
{
_users = new List<User>();
if (DomainExists(ConnectionString))
{
var baseDirectory = new DirectoryEntry(ConnectionString);
baseDirectory.Username = Username;
baseDirectory.Password = Password;
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchRoot = baseDirectory;
searcher.Filter = "(objectCategory=user)";
searcher.SearchScope = SearchScope.Subtree;
var userResults = searcher.FindAll();
foreach (SearchResult user in userResults)
{
var newUser = new User();
newUser.Name = user.Properties["name"][0].ToString();
newUser.Path = user.Path;
_users.Add(newUser);
}
}
return _users;
}
private bool DomainExists(string _connectionString)
{
try
{
if (DirectoryEntry.Exists(_connectionString))
return true;
else
return false;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}
我想知道,有没有办法创建用户使用这个库?
答案 0 :(得分:1)
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
Managing Directory Security Principals in the .NET Framework 3.5
S.DS.AM
命名空间为您提供了很好的强类型类,可以与用户(UserPrincipal
)和组(GroupPrincipal
)一起使用。您可以轻松地使用这些对象并检查和设置它们的属性 - 非常漂亮和干净,不再使用DirectoryEntry
及其混乱的.Properties
以及类似的东西。
基本上,您可以定义域上下文,然后您可以轻松地在AD中搜索和查找用户和/或组以及创建新实体:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// create a user principal object
UserPrincipal user =
new UserPrincipal(ctx, "YourUserNameHere", "pass@1w0rd01", true);
// assign some properties to the user principal
user.GivenName = "User";
user.Surname = "MyNew";
// force the user to change password at next logon
user.ExpirePasswordNow();
// save the user to the directory
user.Save();
新的S.DS.AM使得在AD中使用用户和群组变得非常容易:
答案 1 :(得分:0)
尝试
public void CreateUser(string username)
{
if (DomainExists(ConnectionString))
{
var baseDirectory = new DirectoryEntry(ConnectionString);
DirectoryEntry user = baseDirectory.Children.Add("CN=" + username, "user");
user.Properties["sAMAccountName"].Add(username);
user.CommitChanges();
}
}