83

How do I get the local machine name?

jww
  • 97,681
  • 90
  • 411
  • 885
Yoann. B
  • 11,075
  • 19
  • 69
  • 111
  • Duplicate Question [link](http://stackoverflow.com/questions/459034/get-computer-name-from-within-a-windows-service) – Malachi Apr 18 '13 at 15:56
  • Possible duplicate of [How do I get the computer name in .NET](http://stackoverflow.com/questions/1768198/how-do-i-get-the-computer-name-in-net) – Michael Freidgeim Jan 29 '17 at 11:19

5 Answers5

164

System.Environment.MachineName

It works unless a machine name has more than 15 characters.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
annakata
  • 74,572
  • 17
  • 113
  • 180
  • Sorry :) These little questions are kind of a turkey shoot. I kind of assumed there'd be 4 answers by the time I posted. – annakata Mar 19 '09 at 13:59
  • Just a note, in .NET Standard on Android this seems to return "localhost" – apc Dec 09 '19 at 11:41
53

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: Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Steve
  • 541
  • 3
  • 5
48

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

Liam
  • 27,717
  • 28
  • 128
  • 190
dnewcome
  • 2,045
  • 17
  • 15
20

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

Szilard Muzsi
  • 1,881
  • 2
  • 16
  • 20
  • In computer settings there's a section for Computer Name and Full Computer Name--this is the only way I've found for getting the Full Computer Name when everyone else just gives the Computer Name. Thank you! – user2465164 Sep 21 '17 at 21:43
  • 1
    hmm, just gives `localhost` for me, not `FQDN`. – Thufir Feb 18 '18 at 13:07
  • `localhost` in not needed, you can just provide an empty string: `Dns.GetHostEntry("").HostName`. – Metro Smurf Jun 02 '22 at 21:23
0

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();
Alan Hu
  • 171
  • 2
  • 6