Solved

Convert Console App to Service

Posted on 2009-06-29
5
289 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
ID: 24739868
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
ID: 24739931
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
ID: 24739949
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
ID: 24739995
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
ID: 24740012
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
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!
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

820 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