Solved

Convert Console App to Service

Posted on 2009-06-29
5
288 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

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

803 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