title: How to get the NETBIOS Domain Name using the FQDN in a Complex Environment
body: <p>Getting the NETBIOS domain name from a fully qualified Active Directory domain name is sometimes a tedious task. I found a good answer <a href="https://stackoverflow.com/a/13814584/1027551">here</a>.</p>
  
  <p>In an environment with multiple forests this approach will however not work if the PC is not in the forest you are querying. This is because <code>LDAP://RootDSE</code> will query information for the computer’s domain. </p>
  
  <p>Some might ask: why so complicated? Just use the name before the first dot retrieved by: </p>
  
  <pre><code>ActiveDirectory.Domain.GetComputerDomain().Name;
  </code></pre>
  
  <p>Or just get the user's domain name:</p>
  
  <pre><code>Environment.GetEnvironmentVariable("USERDOMAIN");
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Environment.UserDomainName;
  </code></pre>
  
  <p>BUT the NETBIOS domain name can be something completely different, and you or your computer might be in a different domain or forest!  So this approach is usable only in a simple environment.</p>
  
  <p><a href="https://stackoverflow.com/users/955076/dj-kraze">DJ KRAZE’s</a> solution needs only one small modification to allow cross domain queries. This assumes a trust relationship!</p>
  
  <pre><code>private string GetNetbiosDomainName(string dnsDomainName)
  {
        string netbiosDomainName = string.Empty;
  
        DirectoryEntry rootDSE = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE",dnsDomainName));
  
        string configurationNamingContext = rootDSE.Properties["configurationNamingContext"][0].ToString();
  
        DirectoryEntry searchRoot = new DirectoryEntry("LDAP://cn=Partitions," + configurationNamingContext);
  
        DirectorySearcher searcher = new DirectorySearcher(searchRoot);
        searcher.SearchScope = SearchScope.OneLevel;
        searcher.PropertiesToLoad.Add("netbiosname");
        searcher.Filter = string.Format("(&amp;(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", dnsDomainName);
  
        SearchResult result = searcher.FindOne();
  
        if (result != null)
        {
          netbiosDomainName = result.Properties["netbiosname"][0].ToString();
        }
  
        return netbiosDomainName;
      }
  </code></pre>