从一个窗口服务获得计算机名窗口、计算机

2023-09-04 00:32:16 作者:怂

在一个.NET Windows服务(C#),我怎么能得到计算机名称?

In a .net windows service (C#), how can I get the computer name?

这是一个可靠的方法,或者我应该把它包在try / catch语句?

Is this a reliable method, or should I wrap it in try/catch?

推荐答案

看的环境类。那里有很多的好东西在里面,包括MachineName:

Look at the Environment class. There're lots of nice things in there, including the MachineName:

string CurrentMachineName = Environment.MachineName;

根据文档,这可能会产生一个InvalidOperationException所以你必须要知道这种可能性。风险也许并不保证包装在一个try / catch,虽然。

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.