15 April 2011

Create a Windows Service in .NET That Can Also Run as Console Application

I  want to  create a simple windows service using Visual Studio but  I want to be able to easily test it by simply running the resulting exe without the need to install the service. For that we have to follow the below steps….
  • Create a new Windows Service Project as:
    SNAGHTML14f68ce
  • Once that’s done, you should have a Program.cs and a Service1.cs file in your project. Just delete the Program.cs
  • And now instead add Main method in service1.cs class.
  • Now add Some name to your service say MyService.
  • Now update the code in Main method with the following the code in the following example.
    1 using System;
    2 using System.ServiceProcess;
    3 using System.Timers;
    4
    5 namespace WindowsService1
    6 {
    7 public partial class MyService : ServiceBase
    8 {
    9
    10 public MyService()
    11 {
    12 InitializeComponent();
    13 }
    14
    15 protected override void OnStart(string[] args)
    16 {
    17 Timer ObjPriTimer = new Timer();
    18 ObjPriTimer.Interval = 1000;
    19 ObjPriTimer.Elapsed += new ElapsedEventHandler(ObjPriTimer_Elapsed);
    20 ObjPriTimer.Start();
    21 }
    22
    23 void ObjPriTimer_Elapsed(object sender, ElapsedEventArgs e)
    24 {
    25 Console.WriteLine("Welcome to SukeshMarla.Blogspot.com");
    26 }
    27
    28 protected override void OnStop()
    29 {
    30 }
    31
    32
    33 static void Main(string[] args)
    34 {
    35
    36 MyService ObjPriMyService = new MyService ();
    37 if (Environment.UserInteractive)
    38 {
    39 ObjPriMyService.OnStart(args);
    40 Console.WriteLine("Service started,Press a key to stop!!!");
    41 Console.ReadKey();
    42 ObjPriMyService.OnStop();
    43 }
    44 else
    45 {
    46 Run(ObjPriMyService);
    47 }
    48 }
    49 }
    50 }
    51

  • Now right click the project from the solution explorer and change the Output Type To Console Application
  • Now Press F5 that’s it