C# – Creating a Service to Monitor a
Directory
November 27, 2012, 2:12 pm by Rhyous
http://www.rhyous.com/2012/11/27/c-creating-a-service-to-monitor-a-directory/
Let’s say you wanted to watch a directory and perform an action each time a file is added,
deleted, changed, or renamed.
Microsoft has a Visual C# Windows Service project template in Visual Studio.
Microsoft also has a nice class already created to help with this: FileSystemWatcher
Example Project
Here is an example project you can download: DirectoryMonitoring.zip
Step 1 – Create a Visual C# Windows Service project in Visual Studio
1. Select File | New Project.
2. Select Templates | VIsual C# | Windows | Windows Service.
3. Provide a name: DirectoryMonitoring
4. Click OK.
Step 2 – Create an object that inherits from FileSystemWatcher
1. Right-click on Project and choose Add | Class.
2. Name it MyFileSystemWatcher.cs.
?
01using System;
using System.IO;
02
03
namespace DirectoryMonitoring
04
{
05
public class MyFileSystemWatcher : FileSystemWatcher
06
{
07 public MyFileSystemWatcher()
08 {
09 Init();
10 }
11
public MyFileSystemWatcher(String inDirectoryPath)
12
: base(inDirectoryPath)
13
{
14
Init();
15
}
16
17 public MyFileSystemWatcher(String inDirectoryPath, string
inFilter)
18
: base(inDirectoryPath, inFilter)
19
{
20
Init();
21
}
22
23
private void Init()
24 {
25 IncludeSubdirectories = true;
26 // Eliminate duplicates when timestamp doesn't change
27 NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
// The default also has NotifyFilters.LastWrite
28
EnableRaisingEvents = true;
29 Created += Watcher_Created;
30 Changed += Watcher_Changed;
31 Deleted += Watcher_Deleted;
32 Renamed += Watcher_Renamed;
33 }
34
public void Watcher_Created(object source, FileSystemEventArgs
35inArgs)
36 {
37 Log.WriteLine("File created or added: " + inArgs.FullPath);
38 }
39
public void Watcher_Changed(object sender, FileSystemEventArgs
40
inArgs)
41 {
42 Log.WriteLine("File changed: " + inArgs.FullPath);
43 }
44
45 public void Watcher_Deleted(object sender, FileSystemEventArgs
inArgs)
46
{
47 Log.WriteLine("File deleted: " + inArgs.FullPath);
48 }
49
50 public void Watcher_Renamed(object sender, RenamedEventArgs
inArgs)
51
{
52
Log.WriteLine("File renamed: " + inArgs.OldFullPath + ", New
53name: " + inArgs.FullPath);
54 }
}
55
}
56
57
Notice that each method is logging. We will implement this log next.
Step 3 – Add logging
1. Add the class from a previous post: A simple Log singleton in C#
2. Make sure to change the namespace to match.
Step 4 – Implement the Service
1. Right-click on the Service1.cs file and choose View Code.
2. Change both the Name and the ServiceName to DirectoryMonitoringService. You can
right-click on the file to rename. If that doesn’t rename the class, you can open the file,
right-click on the class name and choose Refactor | Rename.
3. Go to the code of the DirectoryMonitoringService.cs file (which was Service1.cs just a
couple steps ago) in Visual Studio.
4. Implement the constructor as follows:
?
01
using System.IO;
02using System.ServiceProcess;
03
04namespace DirectoryMonitoring
05{
06 public partial class DirectoryMonitoringService: ServiceBase
07 {
protected FileSystemWatcher Watcher;
08
09
// Directory must already exist unless you want to add your own
10code to create it.
11 string PathToFolder = @"C:\Directoy\To\Monitor";
12
13 public Service1()
14 {
Log.Instance.LogPath =
15
@"C:\ProgramData\DirectoryMonitoring";
16 Log.Instance.LogFileName = "DirectoryMonitoring";
17 Watcher = new MyFileSystemWatcher(PathToFolder);
18 }
19
20 protected override void OnStart(string[] args)
21 {
}
22
23
protected override void OnStop()
24
25 {
26 }
}
27
}
28
Step 5 – Create a Service Installer
1. Right-click on DirectoryMonitoringService.cs and choose View Designer.
2. Right-click anywhere in the designer window and choose Add Installer. This adds a
ProjectInstaller.cs file.
3. Right-click on ProjectInstaller.cs and choose View Designer.
4. In the designer, right-click on serviceProcessInstaller1 and choose Properties.
5. In the properties, set Account to LocalSystem.
6. Back in the designer, right-click on serviceInstaller1 and choose Properties.
7. Set StartType to Automatic.
8. Add a descriptions if you want.
Step 6 – Install the Service
1. Open the Developer Command Prompt by right-clicking and choosing Run as
Administrator.
2. In the command prompt, change to the bin\debug folder in your project directory.
3. Run this command to install the service:
installutil.exe DirectoryMonitoring.exe
4. Start the service with this command.
net start DirectoryMonitoringService
Step 7 – Debug the Service
1. Make sure the service is started and running.
2. In Visual Studio with the DirectoryMonitoring project open, click Debug | Attach to
Process.
3. Select the DirectoryMonitoring.exe file.
4. Put a break point at each event in the MyFileSystemWatcher object.
5. Test all four events:
1. Add a file.
2. Rename a file.
3. Open and save a file.
4. Delete a file.
You have now created a service to monitor a directory and you have seen how to debug it.