views:

561

answers:

2

Hi,

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

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

+7  A: 

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.

Michael Haren
We have seen sporadic in-the-field failures, so you should catch the IOE if your code path is critical.
JBRWilkinson
+1  A: 

I think first you have to decide what you mean by "computer name".

As others have said, and possibly "tradionally" 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".

Christian.K