Quick Tip – C# Getting the DNS FQDN of your Active Directory Domain…

Slightly off topic this one, but along the same line as my post here (about getting your Exchange Organization name using C”#) – this was something that has been driving me crazy.

In essence I have been rewriting (for what now seems forever) my Exchange 2007 Segregation tool in C# using Visual Studio. One of the new features of the tool is to dynamically detect the FQDN of the Active Directory Domain which your Exchange Server is a member of.

So for example – if you have a domain called Justice.com – that value would be retuned to a text box within my application.

In initial builds of the software I was using the following code which I found on the Internet via Google:

IPHostEntry he = Dns.GetHostEntry(Environment.UserDomainName);
tboxDNSDomain.Text = he.HostName.ToString();

However, during testing (sic. of the function which detected the DNS domain) I found that the above code would work just fine when the overall application was run on a Windows 2008 Server – however when testing the same code against a Windows 2003 box I would get the following error:

DNS.GetHostEntry = No such host is known – see the screen shot below for the .NET Exception dialog:


After a lot of testing and, quite frankly mucking around I came to the conclusion (which might be unfounded) that there is something different about the Windows 2008 .NET API’s to that are in Windows 2003 – which causes this problem to happen.
Addtionally from my research in online forums it would seem that I am not the only person whom seems to have come across this issue.

So rather than continuing to waste time, I decided to see if I could find another way around the problem – to which I came up with the following code:

using System.Net.NetworkInformation;

IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
tboxDNSDomain.Text = properties.DomainName;

Testing the above code on both Windows platforms yielded success, so; if you are coding in C# and would like to resolve just the FQDN of an Active Directory domain (or more the the point the FQDN of the domain which the machine which you are executing the code on) – the above seems to provide very reliable results.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.