Solved

Convert Console App to Service

Posted on 2009-06-29
5
284 Views
Last Modified: 2013-12-17
I have a little  FileSystemWatcher application that I wrote and would like to turn into a Windows Service.  Currently I'm compiling as a 'Windows Application' (to keep it windowless).  How can I convert this over to a service?  Note:  I've never written a service before.  My current code is below.
// #define TestMode
 

using System;

using System.IO;
 

namespace ProjectWatch

{

    class Program

    {

        static void Main(string[] args)

        {

            FileSystemWatcher projectWatcher = new FileSystemWatcher();

            projectWatcher.Path = @"I:\";

            projectWatcher.EnableRaisingEvents = true;

            projectWatcher.IncludeSubdirectories = true;
 

            projectWatcher.NotifyFilter = NotifyFilters.LastAccess | 

                                          NotifyFilters.LastWrite |

                                          NotifyFilters.DirectoryName | 

                                          NotifyFilters.FileName;
 

            projectWatcher.Deleted += new FileSystemEventHandler(OnChanged);

            projectWatcher.Created += new FileSystemEventHandler(OnChanged);

            projectWatcher.Renamed += new RenamedEventHandler(OnRenamed);

            

            while (Console.Read() != 'q') ;

        }

        

        private static void OnChanged(object source, FileSystemEventArgs e)

        {

            #if (TestMode)

                Console.WriteLine(DateTime.Now);

                Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

                Console.WriteLine("\n");

            #else

                if (e.FullPath.EndsWith(".tmp"))    

                { return; }

                StreamWriter pwLogWrite = File.AppendText(@"C:\projectWatch.log");

                pwLogWrite.WriteLine(DateTime.Now);

                pwLogWrite.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

                pwLogWrite.WriteLine();

                pwLogWrite.Close();

                pwLogWrite = null;

            #endif

        }
 

        private static void OnRenamed(object source, RenamedEventArgs e)

        {

            #if (TestMode)

                Console.WriteLine(DateTime.Now);

                Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);

                Console.WriteLine("\n");

            #else

                if (e.FullPath.EndsWith(".tmp"))

                { return; }    

                StreamWriter pwLogWrite = File.AppendText(@"C:\projectWatch.log");

                pwLogWrite.WriteLine(DateTime.Now);

                pwLogWrite.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);

                pwLogWrite.WriteLine();

                pwLogWrite.Close();

                pwLogWrite = null;

            #endif

        }

    }

}

Open in new window

0
Comment
Question by:thegreekitalian
  • 2
  • 2
5 Comments
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 250 total points
Comment Utility
I would create a new Windows Service project in Visual Studio, then copy/paste your code.

In the services OnStart I would start a new thread, and that thread's code would be your main() from above.

(basically, anyway, but good starting point!)
0
 

Author Comment

by:thegreekitalian
Comment Utility
Ok, attached is a skeleton service.  Where would I paste my code?  Also, to keep the process running I was using while (Console.Read() != 'q') ; What would I use to keep the service actively watching the target?
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Text;
 

namespace ProjectGuardian

{

    public partial class ProjectGuardian : ServiceBase

    {

        public ProjectGuardian()

        {

            InitializeComponent();

        }
 

        protected override void OnStart(string[] args)

        {
 

        }
 

        protected override void OnStop()

        {

        }

    }

}

Open in new window

0
 
LVL 55

Assisted Solution

by:Jaime Olivares
Jaime Olivares earned 250 total points
Comment Utility
There a more things to learn about windows services than just pasting over a template. Have a look to this tutorial:
http://www.codeproject.com/KB/cs/WindowsServicesInAction1.aspx
0
 

Author Comment

by:thegreekitalian
Comment Utility
jaime,

That's a great tutorial!  Thank you.  I'm still not quite sure where to add what I need to add, though.  I have already written the code, I just need to get it where it needs to be (and probably modified a bit).  I will also add the installer, etc (thanks again for that).  
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
When your service is started OnStart will be called.  OnStart will in turn do any necessary setup work (e.g. make sure I:\ exists), and start a new thread.  The new thread will be what was your main(); it'll have an empty for(;;) loop, or while(true).  You'll need to be able to signal your worker thread to exit when OnStop is called.  

Just a starting point, you'll need to see to other details, as Jaime pointed out.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now