0

My program can run as console program or Windows service. However, when program runs as a service, it runs Main(string[] args) too.

And my Main() method have some code that can not use in windows service.

How can I determine if my program is running as a service?

jdphenix
  • 15,022
  • 3
  • 41
  • 74
Kation
  • 61
  • 1
  • 7
  • how you configure your project run as both console and windows service? – Damith Sep 07 '13 at 02:41
  • Um... My vs language is Chinese. I don't know what it is in English. It seem call "Output Type"("输出类型") that under "Default Namespace" TextBox in project setting. Set it to "Console".Then add a "Windows Service" to your project. Open your "WindowsService.cs", you will find a "Add installer"("添加安装程序", maybe English is this) link. Click this link, vs will add a "ProjectInstaller.cs" to your project. – Kation Sep 07 '13 at 03:06
  • Forget to tell you. Add ServiceBase.Run() to your Main method. – Kation Sep 07 '13 at 03:36

1 Answers1

1

One approach is to use command line argument to specify that (and obviously check in Main). I.e. when configuring service set command line argument to "-asservice" and than in Main check if this argument is passed in. I.e.

if(args.Any(a => a == "-asservice"))
{ 
     // running as service...
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • It seems not work for me. args.Length is 0. Am I miss something? – Kation Sep 07 '13 at 03:02
  • @Kation Did you configured path with argument (note that there are 2 types of arguments - http://stackoverflow.com/questions/6182801/how-to-get-the-command-line-arguments-of-a-windows-service be careful to make sure you do set command line arguments for service to be able to check them in `Main`). – Alexei Levenkov Sep 07 '13 at 03:07