What is the best way to determine the name of your computer in a .NET application?

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

+4
source share
3 answers

While others have already said that System.Environment.MachineName returns you the name of the machine, beware ...

This property returns only the NetBIOS name (and only if your application has EnvironmentPermissionAccess.Read permissions). It is possible that your machine name exceeds the length specified in:

MAX_COMPUTERNAME_LENGTH 

In these cases, System.Environment.MachineName will not give you the correct name!

Also note that there are several names that your machine can go through, and in Win32 there is a GetComputerNameEx method that is able to get the name matching each of these different types of names:

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

If you need this information, you probably have to upgrade to Win32 via p / invoke, for example:

 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()); } } 
+6
source

Try Environment.MachineName . Ray really has the best , although you will need to use some interaction code.

+1
source

Source: https://habr.com/ru/post/1276941/


All Articles