我正在尝试设置属性以解锁AD中的用户帐户,并且正在使用以下代码;问题是de
不包含userAccountControl
并且代码失败。
我可以使用userAccountControl
来获取DirectorySearcher
的值,但这对使用de
设置属性没有帮助。谁能帮我吗?提前致谢
String m_Path = "LDAP://" + distinguishedName;
using (DirectoryEntry de = new DirectoryEntry(m_Path))
{
if (de.Contains("userAccountControl")
{
int m_Val = (int)de.Properties["userAccountControl"][0].Value;
de.Properties["userAccountControl"].Value = m_Val | 0x0001
de.CommitChanges;
}
}
最佳答案
我认为您需要检查de.Properties
是否包含userAccountControl
的值!
string ldapPath = "LDAP://" + distinguishedName;
using(DirectoryEntry de = new DirectoryEntry(ldapPath))
{
// check to see if we have "userAccountControl" in the **properties** of de
if(de.Properties.Contains("userAccountControl")
{
int m_Val = (int)de.Properties["userAccountControl"][0].Value ;
de.Properties["userAccountControl"].Value = m_Val | 0x0001;
de.CommitChanges();
}
}
另外,如果您使用的是.NET 3.5及更高版本,则应检出
System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有内容:Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
基本上,您可以定义域上下文,并在AD中轻松查找和操作用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// unlock user
user.UnlockAccount();
}
新的S.DS.AM使得与AD中的用户和组玩起来非常容易!