Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/.NET: Detect whether program is being run as a service or a console application [duplicate]

Tags:

c#

.net

service

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?

like image 261
Rasmus Faber Avatar asked Oct 16 '08 09:10

Rasmus Faber


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

Environment.UserInteractive will do the magic.

like image 153
Vlad Nagorny Avatar answered Sep 19 '22 23:09

Vlad Nagorny


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.)

like image 20
Ash Avatar answered Sep 21 '22 23:09

Ash