C# 在 Windows 服务中获取计算机名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/459034/
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
Get the computer name in a Windows service?
提问by Blankman
In a .NET Windows service (C#), how can I get the computer name?
在 .NET Windows 服务 (C#) 中,如何获取计算机名称?
Is this a reliable method, or should I wrap it in a try/catch?
这是一种可靠的方法,还是应该将其包装在 try/catch 中?
采纳答案by Michael Haren
Look at the Environment class. There're lots of nice things in there, including the MachineName:
看看环境类。那里有很多不错的东西,包括MachineName:
string CurrentMachineName = Environment.MachineName;
According to the docs, this could generate an InvalidOperationException so you'll need to be aware of that possibility. The risk probably doesn't warrant wrapping it in a try/catch, though.
根据文档,这可能会生成 InvalidOperationException,因此您需要注意这种可能性。但是,风险可能并不保证将其包装在 try/catch 中。
回答by Christian.K
I think first you have to decide what you mean by "computer name".
我认为首先您必须确定“计算机名称”的含义。
As others have said, and possibly "traditionally" on windows, you would use the Environment.MachineName
property to get the computer's name, which is actually the NetBIOS name of the machine. Another option would be the (fully qualified) DNS name of the machine. Be aware however, that a single machine could actually have multiple adapters/IP-Addresses/whatever and thus multiple DNS names.
正如其他人所说,并且可能在 Windows 上“传统上”,您将使用该Environment.MachineName
属性来获取计算机的 name,这实际上是机器的 NetBIOS 名称。另一个选项是机器的(完全限定的)DNS 名称。但是请注意,一台机器实际上可能有多个适配器/IP 地址/任何内容,因此有多个 DNS 名称。
Considering the handling of the potential InvalidOperationException
of Environment.MachineName
, I suggest thinking about what you would actually do if you encounter it. If there is something you can do about it, you can and of course should catch it.
考虑到潜在的处理InvalidOperationException
的Environment.MachineName
,我建议什么,如果你遇到了,你就会真正做到思想。如果你能做些什么,你可以而且当然应该抓住它。
For example, in some of my code, I need to get the computer name (incidentally also in a service), but I only use it for diagnostics purposes. If the Environment.MachineName
fails, I just use some "(unknown)"
string in the diagnostics output (and also log an error once).
例如,在我的一些代码中,我需要获取计算机名称(顺便说一下也在服务中),但我仅将其用于诊断目的。如果Environment.MachineName
失败,我只"(unknown)"
在诊断输出中使用一些字符串(并记录一次错误)。
If the result is vital to your further processing you should probably catch the exception also, write the incident to the windows event log and "die".
如果结果对您的进一步处理至关重要,您可能还应该捕获异常,将事件写入 Windows 事件日志并“死”。