I need to get the name of the machine my .NET app is running on. What is the best way to do this?
Whilst others have already said that the System.Environment.MachineName returns you the name of the machine, beware...
That property is only returning the NetBIOS name (and only if your application has EnvironmentPermissionAccess.Read permissions). It is possible for your machine name to exceed the length defined in:
MAX_COMPUTERNAME_LENGTH
In these cases, System.Environment.MachineName will not return you the correct name!
Also note, there are several names your machine could go by and in Win32 there is a method GetComputerNameEx that is capable of getting the name matching each of these different name types:
If you require this information, you're likely to need to go to Win32 through p/invoke, such as:
class Class1
{
enum COMPUTER_NAME_FORMAT
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified
}
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,
[Out] StringBuilder lpBuffer, ref uint lpnSize);
[STAThread]
static void Main(string[] args)
{
bool success;
StringBuilder name = new StringBuilder(260);
uint size = 260;
success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain,
name, ref size);
Console.WriteLine(name.ToString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With