Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Convert Console App to Service

Posted on 2009-06-29
5
Medium Priority
?
294 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 1000 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 1000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

773 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