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

时间:2015-09-30 23:08:54

标签: c# windows hostname uwp

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.

1 个答案:

答案 0 :(得分:15)

您需要使用NetworkInformation.GetHostNames

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

但请注意,此方法将返回多个HostName s。

在我的情况下,它返回四个HostName,其中DisplayName MyComputerName MyComputerName.local 加上两个IP地址。< / p>

所以我想这可能是安全的 -

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


var hostNames = NetworkInformation.GetHostNames();
var hostName = hostNames.FirstOrDefault(name => name.Type == HostNameType.DomainName)?.DisplayName ?? "???";