问题描述
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 HostName
s.
就我而言,它返回四个 HostName
,其中 DisplayName
是 MyComputerName、MyComputerName.local加上两个 IP 地址.
In my case, it returns four HostName
s of which DisplayName
s 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# 中获取本地主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!