Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local host name in C# on a Windows 10 universal app

string machineName = System.Environment.MachineName;

This code doesn't work for me, error code 'Environment' does not contain a definition for 'MachineName'

I'm using Visual Studio 2015 and Universal App with C#

Please also list the namespace I need to use when you post an answer.

like image 465
Jerry Avatar asked Sep 30 '15 23:09

Jerry


People also ask

How do I find my hostname?

Click Start, right-click Computer, and then click Properties. The computer name appears under Computer name, domain, and workgroup settings.

Which method is used to find local host name?

Determining the hostname from the IP address. Sometimes, the only IP address is only available if the computer is in a network, so a hostname would help identify a computer faster. To find out the name of a computer by its IP address, you can use the command “nslookup”.

What is the command for host name?

The /usr/bin/hostname command displays the name of the current host system. Only users with root user authority can set the host name. The mkdev command and the chdev commands also set the host name permanently. Use the mkdev command when you are defining the TCP/IP instance for the first time.


1 Answers

You need to use NetworkInformation.GetHostNames.

var hostNames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();

But note that this method will return multiple HostNames.

In my case, it returns four HostNames of which DisplayNames are MyComputerName, MyComputerName.local plus two IP addresses.

So I guess it's probably safe to do -

using Windows.Networking;
using Windows.Networking.Connectivity;


var hostNames = NetworkInformation.GetHostNames();
var hostName = hostNames.FirstOrDefault(name => name.Type == HostNameType.DomainName)?.DisplayName ?? "???";
like image 99
Justin XL Avatar answered Sep 28 '22 11:09

Justin XL