如何在 Windows 10 通用应用程序上的 C# 中获取本地主机名 [英] How to get local host name in C# on a Windows 10 universal app

查看:19
本文介绍了如何在 Windows 10 通用应用程序上的 C# 中获取本地主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string machineName = System.Environment.MachineName;

此代码对我不起作用,错误代码环境"不包含机器名称"的定义

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

我在 C# 中使用 Visual Studio 2015 和通用应用

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.

推荐答案

您需要使用 NetworkInformation.GetHostNames.

You need to use NetworkInformation.GetHostNames.

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

但是注意这个方法会返回多个HostName.

But note that this method will return multiple HostNames.

就我而言,它返回四个 HostName,其中 DisplayNameMyComputerNameMyComputerName.local加上两个 IP 地址.

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

这篇关于如何在 Windows 10 通用应用程序上的 C# 中获取本地主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆