I am trying to set properties to unlock User accounts in AD and I am using the following code; the problem is that de
does not contain userAccountControl
and the code fails.
I can get the value of userAccountControl
by using DirectorySearcher
but that does not help me in setting the property using de
. Could anyone please help me? Thanks in advance
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;
}
}
I would think you need to check whether de.Properties
contains a value of 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();
}
}
Also, if you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find and manipulate users and/or groups in 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();
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With