title: How can I convert from a SID to an account name in C#
body: <p>I have a C# application that scans a directory and gathers some information.  I would like to display the account name for each file.  I can do this on the local system by getting the SID for the FileInfo object, and then doing:</p>
  
  <pre><code>string GetNameFromSID( SecurityIdentifier sid )
  {
      NTAccount ntAccount = (NTAccount)sid.Translate( typeof( NTAccount ) );
      return ntAccount.ToString();
  }
  </code></pre>
  
  <p>However, this does not work for files on a network, presumably because the Translate() function only works with local user accounts.  I thought maybe I could do an LDAP lookup on the SID, so I tried the following:</p>
  
  <pre><code>string GetNameFromSID( SecurityIdentifier sid )
  {
      string str = "LDAP://&lt;SID=" + sid.Value + "&gt;";
      DirectoryEntry dirEntry = new DirectoryEntry( str );
      return dirEntry.Name;
  }
  </code></pre>
  
  <p>This seems like it will work, in that the access to "dirEntry.Name" hangs for a few seconds, as if it is going off and querying the network, but then it throws a System.Runtime.InteropServices.COMException</p>
  
  <p>Does anyone know how I can get the account name of an arbitrary file or SID?  I don't know much about networking or LDAP or anything.  There's a class called DirectorySearcher that maybe I'm supposed to use, but it wants a domain name, and I don't know how to get that either - all I have is the path to the directory I'm scanning.</p>
  
  <p>Thanks in advance.</p>