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 displaying 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, it's just a matter of getting a list of domains which I can get in FQDN format easily by Getting the DomainCollection
from the Forest you are in. 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 = "";
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));
string sFriendlyName = oNameTranslate.Get((int)ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4);
return sFriendlyName.Replace(@"\", "");
}
catch
{
return "Access Denied";
}
}
If there's an easy way just let me know, but for now this works for me!