Click here to Skip to main content
15,881,381 members
Articles / Programming Languages / C#
Article

How to implement a simple filewatcher Windows service in C#

Rate me:
Please Sign up or sign in to vote.
4.49/5 (45 votes)
23 Apr 20073 min read 417.1K   14.6K   160   54
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


Written By
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

 
Questionfilewatcher fail after EnableRaisingEvents = true; Pin
Jan Lukeš14-May-20 3:58
Jan Lukeš14-May-20 3:58 
Suggestion4 Stars ... 5 If you would fix the main blog with qizhigang fixes Pin
t00lman13-Dec-16 13:43
t00lman13-Dec-16 13:43 
BugWorks once then the service stops Pin
Jed Smith3-Oct-16 10:38
Jed Smith3-Oct-16 10:38 
Questionvery nice Pin
Member 820324421-Mar-16 1:44
Member 820324421-Mar-16 1:44 
QuestionBug Pin
Member773253717-Dec-13 22:35
Member773253717-Dec-13 22:35 
AnswerRe: Bug Pin
sochry11-Aug-16 11:18
sochry11-Aug-16 11:18 
GeneralMy vote of 5 Pin
FranciscoLeon5-Aug-13 4:47
FranciscoLeon5-Aug-13 4:47 
QuestionWatcher.Create event always throw system.IO error Pin
Murtuza A20-May-13 2:51
Murtuza A20-May-13 2:51 
SuggestionThis is a good tutorial Pin
Mick Hemp26-Mar-13 5:07
Mick Hemp26-Mar-13 5:07 
GeneralI give 4 stars Pin
odie0018-Jan-13 6:47
odie0018-Jan-13 6:47 
QuestionCant get the process to hit Events PinPopular
Sarah054-Jan-13 8:42
Sarah054-Jan-13 8:42 
AnswerRe: Cant get the process to hit Events Pin
Member 1021023220-Aug-13 6:44
Member 1021023220-Aug-13 6:44 
GeneralRe: Cant get the process to hit Events Pin
SriniVasan19904-Dec-16 20:03
SriniVasan19904-Dec-16 20:03 
QuestioninstallNETservice Pin
Member 804249119-Apr-12 8:05
Member 804249119-Apr-12 8:05 
QuestionBatch File Error Pin
jaydee7778-Mar-12 7:57
jaydee7778-Mar-12 7:57 
AnswerRe: Batch File Error Pin
Member 49006124-May-12 21:45
Member 49006124-May-12 21:45 
GeneralRe: Batch File Error Pin
Member 1007578224-May-13 21:11
Member 1007578224-May-13 21:11 
Questioncopying/deleting multiple files Pin
bizzare198817-Oct-11 18:22
bizzare198817-Oct-11 18:22 
GeneralMy vote of 4 Pin
qizhigang7-Apr-11 8:47
qizhigang7-Apr-11 8:47 
General4 lines of EVENT HANDLER code need to be added for it to WORK! Pin
qizhigang7-Apr-11 8:41
qizhigang7-Apr-11 8:41 
GeneralRe: 4 lines of EVENT HANDLER code need to be added for it to WORK! Pin
Member 1178019227-Jan-16 20:37
Member 1178019227-Jan-16 20:37 
GeneralMy vote of 5 Pin
Srikanth0313-Dec-10 22:26
Srikanth0313-Dec-10 22:26 
Gr8
Generalthank you this code.. Pin
mk.developer28-Nov-10 20:51
mk.developer28-Nov-10 20:51 
GeneralMy vote of 3 Pin
P JeanCharles16-Nov-10 4:28
P JeanCharles16-Nov-10 4:28 
GeneralGreat work Pin
keyur soni28-Sep-10 1:03
keyur soni28-Sep-10 1:03 

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

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