Get the computer name in a Windows service?

后端 未结 2 1402
走了就别回头了
走了就别回头了 2021-01-04 11:18

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

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

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 11:52

    Look at the Environment class. There're lots of nice things in there, including the 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.

提交回复
热议问题