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

1

8
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.

Tractile answered 30/9, 2015 at 23:8 Comment(2)
just guessing - msdn.microsoft.com/en-us/library/windows/apps/… ?Vinegar
Dosen't seem to work. Can't find that function even I use the Windows.Networking.Connectivity namespaceTractile
S
20

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 ?? "???";
Slotnick answered 1/10, 2015 at 0:51 Comment(1)
You have to include 'using System.Linq;' for this works fine, I guess.Depth

© 2022 - 2024 — McMap. All rights reserved.