tags:

views:

2011

answers:

4

I have a C#/.NET program that can run both as a console application and as a service. Currently I give it a command-line option to start as a console application, but I would like to avoid that.

Is it possible to programmatically detect whether my program is being started as a service?

If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program.

Any ideas?

A: 

I haven't tried it, but it's possible that Process.GetCurrentProcess will help - under console mode the process name would be the same as the executable, whereas I'd expect (and again, please check!) that when running as a service it would be different.

Jon Skeet
I thought that the process was still (usually) the same exe itself, unless you go out of your way to rehost via svchost.exe or similar...
Marc Gravell
Could be - hard to test from my current desk :(
Jon Skeet
At least under mono, the process name does change to the executing entity (i.e. if run with mono-service the process is now called mono-service). Haven't tried as a windows service
Arne Claassen
+3  A: 

Rasmus, this is the earlier question.

From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process and trying to access it throws an exception).

Or if you're having trouble testing/debugging the service, move code into a separate dll assembly and create a seprate test harness (winforms/console etc).

(Just noticed that Jonathan has added his solution to the end of the question.)

Ash
+1  A: 

Environment.UserInteractive will do the magic.

Vlad Nagorny
What if the service is running on Windows XP with "Allow this service to interact with the desktop" set?
taspeotis
It will stop doing magic, that's what :)
Ishmaeel
A: 

I don't know if this will work, but you may want to try using PInvoke with this code and checking if the parent is "services.exe".

taspeotis