如何在 C# 中获取本地机器名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/662282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:21:41  来源:igfitidea点击:

How do I get the local machine name in C#?

c#dnshostname

提问by Yoann. B

How do I get the local machine name?

如何获取本地机器名称?

回答by dnewcome

You should be able to use System.Environment.MachineNamefor this. It is a property that returns a string containing the netBIOS name of the computer:

你应该可以使用System.Environment.MachineName这个。它是一个返回包含计算机 netBIOS 名称的字符串的属性:

http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx

http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx

回答by Steve

From link text

来自 链接文本

Four ways to get your local network/machine name:

获取本地网络/机器名称的四种方法:

string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable("COMPUTERNAME");

More information at: Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName

更多信息请访问: SystemInformation.ComputerName、Environment.MachineName 和 Net.Dns.GetHostName 之间的区别

回答by Szilard Muzsi

If you want the FQDN (fully qualified domain name) of the local computer, you can use

如果想要本地计算机的 FQDN(完全限定域名),可以使用

System.Net.Dns.GetHostEntry("localhost").HostName

System.Net.Dns.GetHostEntry("localhost").HostName

The other methods will only return the local name, without any domain specific info. For instance, for the computer myComp.myDomain.com, the previous methods will return myComp, whereas the GetHostEntrymethod will return myComp.myDomain.com

其他方法只会返回本地名称,没有任何特定于域的信息。例如,对于计算机myComp.myDomain.com,前面的方法将返回myComp,而该GetHostEntry方法将返回myComp.myDomain.com

回答by Alan Hu

My computer name is more than 15 chars, so i use hostname.exe to get full length name:

我的计算机名称超过 15 个字符,因此我使用 hostname.exe 获取全长名称:

Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = "c:/windows/system32/hostname.exe";
proc.Start();
var hostName = proc.StandardOutput.ReadLine();