Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to implement a simple filewatcher Windows service in C#

4.49/5 (45 votes)
23 Apr 20073 min read 1   14.6K  
This article explains the basic techniques and VS.NET project structure for creating and implementing a simple C# FileSystemWatcher Windows Service

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:

XML
<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:

plain
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():

C#
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:

C#
/* 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:

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