Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Convert Console App to Service

Posted on 2009-06-29
5
Medium Priority
?
292 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

URL rewriting in AWS CloudFront

A quick how-to guide to implement with a Lambda function!

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

660 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