Click here to Skip to main content
Click here to Skip to main content

How to implement a simple filewatcher Windows service in C#

By , 23 Apr 2007
Rate this:
Please Sign up or sign in to vote.

Introduction

This article will briefly explain how to set up a simple "File Watcher/ Directory Watcher" application to run as a Windows Service using Visual Studio 2005. The coding language used is C#.

Background

You must have a machine running Microsoft .NET Framework 2.0+.

Using the code

First, open Visual Studio.NET and create a new Windows Service project for C#:

Screenshot - new_project.jpg

I named this sample solution TestCSWinWatcherService and optionally, chose to create a directory for the solution file.

Next, an appropriate reference must be added to the project as we will be using an application configuration file. Add a reference to "System.Configuration" by right-clicking on the project, then "Add Reference...":

Screenshot - references.jpg

Now, add a new Application Configuration File to the project. We will use this to define a directory (path) to "watch":

Screenshot - app_config.jpg

I left this named as App.config.

Within the configuration which we've just added, we will need to add an "appSettings" section, where we'll define our directory path:

<appSettings>
    <add key="WatchPath" value="C:\\temp\\watch_directory\\" />
</appSettings>

This should go directly below the configuration tag.

We can now set up our code, controls and properties for the actual service...

First, create the main FileSystemWatcher component in the Service1.cs file. This can simply be dragged and dropped from the toolbox:

Screenshot - fs_watcher_control.jpg

In the properties of this newly added control, change the name to something meaningful. I used FSWatcherTest as the name. Additionally, the following properties should be set as follows:

EnableRasingEvents True
Filter *.*
GenerateMember True
IncludeSubdirectories True
Modifiers Private
NotifyFilter FileName, DirectoryName, Attributes, Size, LastWrite, 
                LastAccess, CreationTime, Security

Now that the actual control is created, switch to the code view for Service1.cs and add the code to the OnStart() event, which gets fired when the service starts:

  1. Add the following reference at the top: using System.Configuration;
  2. Add the following code for OnStart():

protected override void OnStart(string[] args)
{
    // TODO: Add code here to start your service.
    FSWatcherTest.Path = ConfigurationManager.AppSettings["WatchPath"];
}

(Optionally, code can similarly be added to the OnStop() event.)

Next, the FileSystem events need to be set up in the Designer code. These will trigger actions associated with file creation, deletion, etc. for the directory path that we set in our app.config file. Add the following to the Service1.designer.cs file (this should be placed right below the instantiation of the FSWatcherTest object:

/* DEFINE WATCHER EVENTS... */
/// <summary>
/// Event occurs when the contents of a File or Directory are changed
/// </summary>
private void FSWatcherTest_Changed(object sender, 
                System.IO.FileSystemEventArgs e)
{
    //code here for newly changed file or directory
}
/// <summary>
/// Event occurs when the a File or Directory is created
/// </summary>
private void FSWatcherTest_Created(object sender, 
                System.IO.FileSystemEventArgs e)
{
    //code here for newly created file or directory
}
/// <summary>
/// Event occurs when the a File or Directory is deleted
/// </summary>
private void FSWatcherTest_Deleted(object sender, 
                System.IO.FileSystemEventArgs e)
{
    //code here for newly deleted file or directory
}
/// <summary>
/// Event occurs when the a File or Directory is renamed
/// </summary>
private void FSWatcherTest_Renamed(object sender, 
                System.IO.RenamedEventArgs e)
{
    //code here for newly renamed file or directory
}

Add whatever code is necessary within each event, and it will get executed when the event is fired. For example, if you want to copy a file that is dropped into your defined "watch" directory, you would use something like this within the FSWatcherTest_Created() event:

System.IO.File.Copy(e.FullPath, "C:\\temp\\archive\\" + e.Name);

Lastly, go into the properties for Service1.cs (in design), and change the ServiceName property to something meaningful. I used TestCSFileSysWatcher. This will be the actual name that shows up in the "Services" window in the Control Panel, once the service is installed.

The last item at hand for completion of this project is to create the windows installer class to allow the project to be compiled as a Windows service. In order to accomplish this, we must first add an InstallerClass file to our project ("Project->Add New Item..."):

Screenshot - installer_class.jpg

(I left this file named as Installer1.cs.)

Now, we need to add two new components to the class- a ServiceInstaller and ServiceProcessInstaller installer. Drag and Drop both onto the file design. If these components are NOT located in the toolbox, simply right-click on the toolbox, and then "Choose Items.." to add them:

Screenshot - new_components.jpg

On the properties for serviceInstaller1, set the ServiceName to TestCSWinWatcherService. I left the StartType property as Manual.

For the serviceProcessInstaller, set the Account property to LocalSystem. This will enable the service to be run as a local system account.

Now, simply Build TestCSWinWatcherService (from the Build menu), and all necessary installer files will be created within the project directory. To install the newly created service, you must use the .NET Framework InstallUtil program. I have included two batch files within this project- one to install the service, and another to UNinstall it. Each can be reused. Simply replace the PROG variable with the name of the service that you are installing or uninstalling.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Matt Sciotto
Web Developer
United States United States
Matt Sciotto is an IT professional, who specializes in VB and .Net software/web application development. He has written several embeddable ActiveX COM controls, as well as custom server controls in VB.Net, and many scalable webform applications. In addition, he has a handy background in server scripting including knowlege of PHP,Perl,CGI and ASP, and Database Management with intense SQL foundation in MS SQL Server, MS Access, Oracle and MySql environments. He has worked on several OS platforms including all recent versions of Windows, Red Hat Linux, FreeBSD, UNIX and Solaris.

Comments and Discussions

 
QuestionBug PinmemberMember773253717-Dec-13 22:35 
GeneralMy vote of 5 PinmemberFranciscoLeon5-Aug-13 4:47 
QuestionWatcher.Create event always throw system.IO error PinmemberMurtuza A20-May-13 2:51 
SuggestionThis is a good tutorial PinmemberMick Hemp26-Mar-13 5:07 
GeneralI give 4 stars Pinmemberodie0018-Jan-13 6:47 
QuestionCant get the process to hit Events PinmemberSarah054-Jan-13 8:42 
AnswerRe: Cant get the process to hit Events PinmemberMember 1021023220-Aug-13 6:44 
QuestioninstallNETservice PinmemberMember 804249119-Apr-12 8:05 
QuestionBatch File Error Pinmemberjaydee7778-Mar-12 7:57 
AnswerRe: Batch File Error PinmemberMember 49006124-May-12 21:45 
GeneralRe: Batch File Error PinmemberMember 1007578224-May-13 21:11 
Questioncopying/deleting multiple files Pinmemberbizzare198817-Oct-11 18:22 
GeneralMy vote of 4 Pinmemberqizhigang7-Apr-11 8:47 
General4 lines of EVENT HANDLER code need to be added for it to WORK! Pinmemberqizhigang7-Apr-11 8:41 
GeneralMy vote of 5 PinmemberSrikanth0313-Dec-10 22:26 
Generalthank you this code.. Pinmembermk.developer28-Nov-10 20:51 
GeneralMy vote of 3 PinmemberP JeanCharles16-Nov-10 4:28 
GeneralGreat work Pinmemberkeyur soni28-Sep-10 1:03 
GeneralInstallation error PinmemberMember 404808427-May-10 14:09 
GeneralRe: Installation error Pinmemberstuallenii18-Jan-11 3:52 
GeneralRe: Installation error Pinmembershashankkale19-Apr-11 19:53 
GeneralBAT File Install Error PinmemberQuinntyne25-Nov-09 9:23 
GeneralRe: BAT File Install Error Pinmemberfredclown15-Nov-10 5:56 
GeneralGood article, thank you. Pinmemberaandonian10-Sep-09 18:06 
GeneralService Started and stopped. Pinmembersandeepam23-Mar-09 11:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 23 Apr 2007
Article Copyright 2007 by Matt Sciotto
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid