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

How to implement a simple filewatcher Windows service in C#

, 23 Apr 2007
Rate this:
Please Sign up or sign in to vote.
This article explains the basic techniques and VS.NET project structure for creating and implementing a simple C# FileSystemWatcher Windows Service


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#.


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:

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

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:

/// <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.


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 23:35 
GeneralMy vote of 5 PinmemberFranciscoLeon5-Aug-13 5:47 
QuestionWatcher.Create event always throw system.IO error PinmemberMurtuza A20-May-13 3:51 
SuggestionThis is a good tutorial PinmemberMick Hemp26-Mar-13 6:07 
GeneralI give 4 stars Pinmemberodie0018-Jan-13 7:47 
QuestionCant get the process to hit Events PinmemberSarah054-Jan-13 9:42 
AnswerRe: Cant get the process to hit Events PinmemberMember 1021023220-Aug-13 7:44 
QuestioninstallNETservice PinmemberMember 804249119-Apr-12 9:05 
QuestionBatch File Error Pinmemberjaydee7778-Mar-12 8:57 
AnswerRe: Batch File Error PinmemberMember 49006124-May-12 22:45 
GeneralRe: Batch File Error PinmemberMember 1007578224-May-13 22:11 
Questioncopying/deleting multiple files Pinmemberbizzare198817-Oct-11 19:22 
GeneralMy vote of 4 Pinmemberqizhigang7-Apr-11 9:47 
General4 lines of EVENT HANDLER code need to be added for it to WORK! Pinmemberqizhigang7-Apr-11 9:41 
GeneralMy vote of 5 PinmemberSrikanth0313-Dec-10 23:26 
Generalthank you this code.. Pinmembermk.developer28-Nov-10 21:51 
GeneralMy vote of 3 PinmemberP JeanCharles16-Nov-10 5:28 
GeneralGreat work Pinmemberkeyur soni28-Sep-10 2:03 
GeneralInstallation error PinmemberMember 404808427-May-10 15:09 
GeneralRe: Installation error Pinmemberstuallenii18-Jan-11 4:52 
GeneralRe: Installation error Pinmembershashankkale19-Apr-11 20:53 
GeneralBAT File Install Error PinmemberQuinntyne25-Nov-09 10:23 
GeneralRe: BAT File Install Error Pinmemberfredclown15-Nov-10 6:56 
GeneralGood article, thank you. Pinmemberaandonian10-Sep-09 19:06 
GeneralService Started and stopped. Pinmembersandeepam23-Mar-09 12:02 
GeneralRe: Service Started and stopped. Pinmembersuper18-Apr-09 3:08 
GeneralRe: Service Started and stopped. PinmemberJohn Marushin14-May-09 8:33 
GeneralRe: Service Started and stopped. Pinmembertestermia20-Dec-09 2:57 
SuggestionRe: Service Started and stopped. Pinmembercraig.wenger23-Jun-11 15:02 
Generalquestion for large files Pinmemberstored27-Jan-09 11:12 
AnswerRe: Question for large files (Suggested answer) Pinmember0xfeeddeadbeef28-Jan-10 9:03 
QuestionSmoking crack? PinmemberDiesel0117-Oct-08 20:38 
QuestionRestricted User cannot start the service PinmemberAPG-111110-Apr-08 5:57 
Questionwatch exchange? PinmemberAaran Heavey6-Apr-08 23:42 
Questionservice name not displayed Pinmembercelestialcitizen29-Dec-07 21:07 
AnswerRe: service name not displayed PinmemberNhilesh B18-Oct-08 2:51 
QuestionCant get any FileSystemEventArgs triggered. Pinmemberakai8018-Aug-07 1:03 
AnswerRe: Cant get any FileSystemEventArgs triggered. Pinmembermarkpdx8-Sep-07 11:52 
GeneralRe: Cant get any FileSystemEventArgs triggered. PinmemberEmpire One6-Aug-08 11:08 
AnswerRe: Cant get any FileSystemEventArgs triggered. Pinmemberphykell3-Oct-08 15:26 
GeneralRe: Cant get any FileSystemEventArgs triggered. Pinmemberbck717117-Apr-10 7:16 
GeneralAppreciation and one suggestion ... PinmemberBillWoodruff4-May-07 2:28 
GeneralProcess Currently is used by Another user PinmemberSridhar raju garapati23-Apr-07 19:04 
AnswerRe: Process Currently is used by Another user Pinmemberperanb1-May-07 0:29 
GeneralGreat walkthrough Pinmembertrevorde stickman23-Apr-07 16:39 
GeneralRe: Great walkthrough Pinmemberluckyshah11-Feb-09 0:54 
GeneralRe: Great walkthrough Pinmemberseab12158024-Feb-09 18:45 

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 | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 23 Apr 2007
Article Copyright 2007 by Matt Sciotto
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid