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

别说谁变了你拦得住时间么 提交于 2019-11-28 00:23:52

问题


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:


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 ?? "???";


来源:https://stackoverflow.com/questions/32876966/how-to-get-local-host-name-in-c-sharp-on-a-windows-10-universal-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!