How do I get the local machine name in C#?

C#DnsHostname

C# Problem Overview


How do I get the local machine name?

C# Solutions


Solution 1 - C#

Solution 2 - C#

From source

Four ways to get your local network/machine name:

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

More information at: https://stackoverflow.com/questions/1233217/difference-between-systeminformation-computername-environment-machinename-and-n

Solution 3 - C#

You should be able to use System.Environment.MachineName for this. It is a property that returns a string containing the netBIOS name of the computer:

http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx

Solution 4 - C#

If you want the FQDN (fully qualified domain name) of the local computer, you can use

System.Net.Dns.GetHostEntry("localhost").HostName

The other methods will only return the local name, without any domain specific info. For instance, for the computer myComp.myDomain.com, the previous methods will return myComp, whereas the GetHostEntry method will return myComp.myDomain.com

Solution 5 - C#

My computer name is more than 15 chars, so i use hostname.exe to get full length name:

Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = "c:/windows/system32/hostname.exe";
proc.Start();
var hostName = proc.StandardOutput.ReadLine();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoann. BView Question on Stackoverflow
Solution 1 - C#annakataView Answer on Stackoverflow
Solution 2 - C#SteveView Answer on Stackoverflow
Solution 3 - C#dnewcomeView Answer on Stackoverflow
Solution 4 - C#Szilard MuzsiView Answer on Stackoverflow
Solution 5 - C#Alan HuView Answer on Stackoverflow