tags:

views:

245

answers:

3

I need to get the name of the machine my .NET app is running on. What is the best way to do this?

+6  A: 

System.Environment.MachineName

Bill Ayakatubby
+1  A: 

Try Environment.MachineName. Ray actually has the best answer, although you will need to use some interop code.

Scott Dorman
+5  A: 

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:

  • ComputerNameDnsDomain
  • ComputerNameDnsFullyQualified
  • ComputerNameDnsHostname
  • ComputerNameNetBIOS
  • ComputerNamePhysicalDnsDomain
  • ComputerNamePhysicalDnsFullyQualified
  • ComputerNamePhysicalDnsHostname
  • ComputerNamePhysicalNetBIOS

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());
    }
}
Ray Hayes
That would require SecurityPermissionFlag.UnmanagedCode, no?
icelava
Probably, but my original justification for pointing out the need for SecurityPermissionFlags was that no-one was mentioning it at all. I'd say in generally most of the permissions are granted, which left the situations where the name is too long or a specific name type is needed.
Ray Hayes