This started when I saw a question on stack overflow and it challenged me to solve it, it may look simple initially but least to say it was challenging. The question was about getting a list of all domain names in your network and display it in a friendly way like what you see when you log on to windows rather than yourdepartment.yourdomain.com
All you have to do is to refer to a COM Reference called Active DS Library which contains the IADsNameTranslate interface which can translate distinguished names (DNs) among various formats.
Now having that tool, its just a matter of getting a list of domain which I can get in FQDN format easily by Getting the DomainCollection from the Forest you are in, now the last issue is converting that FQDN to a DN format which is easy by using String Methods, we are doing this as the reference I mentioned above can only convert from other formats which is defined here and FQDN is not an option so the easiest would be DN. And here is how I did it.
using System.DirectoryServices.ActiveDirectory; using ActiveDs; private void ListDomains() { string sUserName = "xxxx"; string sPassword = "xxxx"; DirectoryContext oDirectoryContext = new DirectoryContext(DirectoryContextType.Domain, sUserName, sPassword); Domain oCurrentDomain = Domain.GetDomain(oDirectoryContext); Forest oForest = oCurrentDomain.Forest; DomainCollection oAddDomainsInForest = oForest.Domains; foreach (Domain oDomain in oAddDomainsInForest) { Console.WriteLine(GetName(oDomain.ToString())); } } private string GetName(string sDomainName) { try { IADsADSystemInfo oSysInfo = new ADSystemInfoClass(); IADsNameTranslate oNameTranslate = new NameTranslateClass(); oNameTranslate.Init((int)ADS_NAME_INITTYPE_ENUM.ADS_NAME_INITTYPE_DOMAIN, sDomainName); string[] aSplitDN = sDomainName.Split(new Char[] { '.' }); string sDistinguishedName = ""; //Convert Domain Name to Distinguished Name foreach (string sDomainPart in aSplitDN) { sDistinguishedName = sDistinguishedName + "DC=" + sDomainPart + ","; } oNameTranslate.Set((int)ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_UNKNOWN, sDistinguishedName.Remove(sDistinguishedName.Length - 1));//Remove the last comma string sFriendlyName = oNameTranslate.Get((int)ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4); return sFriendlyName.Replace(@"", ""); } catch { return "Access Denied"; }
If theres an easy way just let me know, but for now this works for me!