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?
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.
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.
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.
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).
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With