Getting the NETBIOS domain name from a fully qualified Active Directory domain name is sometimes a tedious task. I found a good answer here.
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 LDAP://RootDSE
will query information for the computer’s domain.
Some might ask: why so complicated? Just use the name before the first dot retrieved by:
ActiveDirectory.Domain.GetComputerDomain().Name;
Or just get the user's domain name:
Environment.GetEnvironmentVariable("USERDOMAIN");
or
Environment.UserDomainName;
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.
DJ KRAZE’s solution needs only one small modification to allow cross domain queries. This assumes a trust relationship!
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("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", dnsDomainName);
SearchResult result = searcher.FindOne();
if (result != null)
{
netbiosDomainName = result.Properties["netbiosname"][0].ToString();
}
return netbiosDomainName;
}