.Net Tips — Find out if your app is running as a service

When you are devel­op­ing an appli­ca­tion to run as a ser­vice it’s nice to be able to also run it as a con­sole app so you can eas­i­ly debug, etc. On the rare occa­sion you might even want to find out if your app is run­ning in a con­sole win­dow at run­time so you can set the title of the con­sole win­dow to dis­play some use­ful debug­ging infor­ma­tion, for exam­ple.

After some quick dig­ging around, I found a rel­e­vant ques­tion on Stack­Over­flow and the answer here, all you need is a sim­ple method like this:

   1: public bool IsService()

   2: {

   3:     var entryAssembly = Assembly.GetEntryAssembly();

   4:     var entryPoint = entryAssembly.EntryPoint;


   6:     // add a little error handling to make sure there is a BaseType

   7:     return

   8:         entryPoint.ReflectedType.BaseType != null &&

   9:         entryPoint.ReflectedType.BaseType.FullName == "System.ServiceProcess.ServiceBase";

  10: }