Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName

From what I have seen, in the MSDN documentation and in other questions here on SO, there are four ways to get the local machine name.

Environment.MachineName;
System.Net.Dns.GetHostName();
System.Windows.Forms.SystemInformation.ComputerName;
System.Environment.GetEnvironmentVariable("COMPUTERNAME");

Is there a differnece in what they methods will return or will they all return the exact same thing all of the time?

Note: I first saw the list in this post: How do I get the local machine Name?


Solution 1:

Environment.MachineName and System.Windows.Forms.SystemInformation.ComputerName are identical and returns the computer's NetBIOS name. This name is restricted to 15 characters and only visible on the LAN.

System.Net.Dns.GetHostName() returns the computer's TCP/IP based hostname. By adding a domain suffix to the hostname you can resolve your computer's IP address across LANs / on the internet.

System.Environment.GetEnvironmentVariable("COMPUTERNAME") returns the computer name set during installation. NetBIOS and hostname are initially set to the same name.

Solution 2:

There are some important differences between these methods. Say that you name your computer to "GöransLilla人物987654321".
Environment.MachineName will then return GÖRANSLILLA人物98. That is truncated and all upper case.
Dns.GetHostName will return GöransLilla??987654321. Full length and correct casing but the Chinese multibyte characters have been replaced with '?'. The Swedish 'ö' is kept though.

The only way I know of getting the actual name as specified in Windows is with pinvoke.

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType, System.Text.StringBuilder lpBuffer, ref uint lpnSize);

System.Text.StringBuilder nameBuilder = new System.Text.StringBuilder(260);
uint size = 260;
bool success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsHostname, nameBuilder, ref size);
Console.WriteLine(nameBuilder.ToString());

Solution 3:

Environment.MachineName : NetBIOS name of local computer read from registry

Dns.GetHostName : Gets host name of computer which refers to a domain name that has one or more associated IP adresses.

System.Windows.Forms.SystemInformation.ComputerName : same as Environment.MachineName, difference is you can call this from both web page and windows applications.Environment is used only Windows applications.

Environment.GetEnvironmentVariable method is used to retrieve environment variable from the current process.For more information , you may look at :
http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx