启动账户:
DirectoryEntry usr =
new
DirectoryEntry(
"
LDAP://CN=New User,CN=users,DC=fabrikam,DC=com
"
);
int
val = (
int
) usr.Properties[
"
userAccountControl
"
].Value;
usr.Properties[
"
userAccountControl
"
].Value = val & ~(
int
)ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE;
//=544
usr.CommitChanges();
停用账户:
DirectoryEntry usr =
new
DirectoryEntry(
"
LDAP://CN=Old User,CN=users,DC=fabrikam,DC=com
"
);
int
val = (
int
) usr.Properties[
"
userAccountControl
"
].Value;
usr.Properties[
"
userAccountControl
"
].Value = val |
(
int
)ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE;
//=546
usr.CommitChanges();
ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE值需要引用库才可使用;
引用COM组件: Active DS Type Library
---------------------------------------------------
关于创建用户主要碰到了两个问题:
一、就是上面的启动/停用的问题
二、就是密码设置问题
创建用户,使用usr.Properties["userPassword"].add("m12345.");设置密码,密码一直没有设置成功,原因不详[大概userPassword不是存储密码的吧...]。
之后改为 usr.Invoke("SetPassword","m12345.");就成功了.
修改密码使用usr.Invoke("ChangePassword", new object[] { "old", "new" });
---------------------------------------------------
关于.net3.5之后的版本(应该吧)有一个更简洁的方法创建用户修改密码等。
创建用户:
using
(
var
context =
new
PrincipalContext(ContextType.Domain,
"
cninnovation
"
))
using
(
var
user =
new
UserPrincipal(context,
"
Tom
"
,
"
P@ssw0rd
"
,
true
)
{
GivenName
=
"
Tom
"
,
EmailAddress
=
"
test@test.com
"
})
{
user.Save();
}
重置密码:
using
(
var
context =
new
PrincipalContext(ContextType.Domain,
"
cninnovation
"
))
using
(
var
user =
UserPrincipal.FindByIdentity(context, IdentityType.Name,
"
Tom
"
))
{
user.SetPassword(
"
Pa$$w0rd
"
);
user.Save();
}
创建组:
using
(
var
ctx =
new
PrincipalContext(ContextType.Domain,
"
cninnovation
"
))
using
(
var
group =
new
GroupPrincipal(ctx)
{
Description
=
"
Sample group
"
,
DisplayName
=
"
Wrox Authors
"
,
Name
=
"
WroxAuthors
"
})
{
group.Save();
}
组中添加用户:
using
(
var
context =
new
PrincipalContext(ContextType.Domain))
using
(
var
group =
GroupPrincipal.FindByIdentity(context, IdentityType.Name,
"
WroxAuthors
"
))
using
(
var
user =
UserPrincipal.FindByIdentity(context, IdentityType.Name,
"
Stephanie Nagel
"
))
{
group.Members.Add(user);
group.Save();
}
查找用户:
using
(
var
context =
new
PrincipalContext(ContextType.Domain,
"
explorer
"
))
using
(
var
users =
UserPrincipal.FindByPasswordSetTime(context, DateTime.Today
-TimeSpan.FromDays(
30
), MatchType.LessThan))
{
foreach
(
var
user
in
users)
{
Console.WriteLine(
"
{0}, last logon: {1},
"
+
"
last password change: {2}
"
, user.Name, user.LastLogon, user.LastPasswordSet);
}
}
var
context =
new
PrincipalContext(ContextType.Domain);
var
userFilter =
new
UserPrincipal(context);
userFilter.Surname
=
"
Nag*
"
;
userFilter.Enabled
=
true
;
using
(
var
searcher =
new
PrincipalSearcher())
{
searcher.QueryFilter
=
userFilter;
var
searchResult =
searcher.FindAll();
foreach
(
var
user
in
searchResult)
{
Console.WriteLine(user.Name);
}
}
参考资料: http://msdn.microsoft.com/zh-tw/library/ms180913(v=vs.90).aspx

