问题描述
string machineName = System.Environment.MachineName;
此代码对我不起作用,错误代码"Environment"不包含"MachineName"的定义
This code doesn't work for me, error code 'Environment' does not contain a definition for 'MachineName'
我正在将Visual Studio 2015和Universal App与C#一起使用
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#中获取本地主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!