title: Active Directory Acquiring Locked/Unlocked status in a Windows Service
body: <p>I am making a <strong>Windows Service</strong> that gets the Locked/Unlocked status of all Active Directory accounts in my local domain TRY.local.
  Even though the account with the name user1 is locked, it gives <strong>false</strong> value for <strong>IsAccountLocked()</strong>.</p>
  <pre><code>using (var context = new PrincipalContext(ContextType.Domain, &quot;TRY.local&quot;))
  {
      using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
      {
          foreach (var result in searcher.FindAll())
          {
              DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
              Library.WriteErrorLog(&quot;First Name: &quot; + de.Properties[&quot;givenName&quot;].Value);
              try{
                  string name = (string)de.Properties[&quot;samaccountname&quot;].Value;
                  PrincipalContext ctx = new PrincipalContext(ContextType.Domain,&quot;TRY.local&quot;,&quot;CN=&quot;+name+&quot;,OU=Users,DC=TRY,DC=local&quot;,&quot;administrator&quot;,&quot;password&quot;);
                  UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, name);
                  if(usr!=null){
                      Library.WriteErrorLog(&quot;IsAccountLockedOut\t&quot;+usr.IsAccountLockedOut());
                  }
                  usr.Dispose();
                  ctx.Dispose();
              }
          catch(Exception e){                                         
              Library.WriteErrorLog(e);
          }
      }
  }
  </code></pre>
  <p>I also tried</p>
  <pre><code>using (var context = new PrincipalContext(ContextType.Domain, &quot;TRY.local&quot;))
  {
      using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
      {
          foreach (var result in searcher.FindAll())
          {
              DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
              Library.WriteErrorLog(&quot;SAM Account Name : &quot; + de.Properties[&quot;samaccountname&quot;].Value);
              int uc = Convert.ToInt32(de.Properties[&quot;userAccountControl&quot;][0]);
              const int ADS_LOCKOUT = 0x00000010;
              bool account_LockedOut = (uc &amp; ADS_LOCKOUT)==ADS_LOCKOUT;
              Library.WriteErrorLog(&quot;IsAccountLockedOut : &quot;+account_LockedOut);                                       
          }
      }
  }
  </code></pre>
  <p>WriteErrorLog(string abc) writes abc to a textfile<img src="https://i.stack.imgur.com/xSJK5.jpg" alt="It gives false even if the account is Locked" /></p>
  <p><img src="https://i.stack.imgur.com/jMVc7.jpg" alt="user1 is Locked" /></p>
  <p>I would be very grateful if I could get guidance on this issue as I am new to Active Directory.
  Thanks in Advance!</p>