title: How to check if Windows user account name exists in domain?
body: <p>What is the simplest and most efficient way in C# to check if a Windows user account name exists?  This is in a domain environment.</p>
  
  <ul>
  <li>Input: user name in [domain]/[user] format (e.g. "mycompany\bob")</li>
  <li>Output: True if the user name exists, false if not.</li>
  </ul>
  
  <p>I did find <a href="http://www.codeproject.com/KB/system/everythingInAD.aspx" rel="noreferrer">this article</a> but the examples there are related to authenticating and manipulating user accounts, and they assume you already have a user distinguished name, whereas I am starting with the user account name.</p>
  
  <p>I'm sure I can figure this out using AD, but before I do so I was wondering if there is a simple higher level API that does what I need.</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>There are probably many ways to do this, Russ posted one that could work but I couldn't figure out how to tweak it to work in my environment.  I did find a different approach, using the WinNT provider that did the job for me:</p>
  
  <pre><code>    public static bool UserInDomain(string username, string domain)
      {
          string path = String.Format("WinNT://{0}/{1},user", domain, username);
  
          try
          {
              DirectoryEntry.Exists(path);
              return true;
          }
          catch (Exception)
          {
              // For WinNT provider DirectoryEntry.Exists throws an exception
              // instead of returning false so we need to trap it.
              return false;
          }
      }
  </code></pre>
  
  <p><em>P.S.</em>
  For those who aren't familiar with the API used above: you need to add a reference to System.DirectoryServices to use it.</p>
  
  <p>The link I found that helped me with this: <a href="http://forums.aspfree.com/showpost.php?p=38827&amp;postcount=3" rel="noreferrer">How Can I Get User Information Using ADSI</a>
  The examples use ADSI but can be applied to .NET DirectoryServices as well.  They also demonstrate other properties of the user object that may be useful.</p>