C# - Creating A Service To Monitor A Directory
C# - Creating A Service To Monitor A Directory
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.
Example Project
?
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
23
private void Init()
24 {
25 IncludeSubdirectories = true;
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
49
54 }
}
55
}
56
57
Notice that each method is logging. We will implement this log next.
?
01
using System.IO;
02using System.ServiceProcess;
03
04namespace DirectoryMonitoring
05{
07 {
09
// Directory must already exist unless you want to add your own
10code to create it.
12
13 public Service1()
14 {
Log.Instance.LogPath =
15
@"C:\ProgramData\DirectoryMonitoring";
16 Log.Instance.LogFileName = "DirectoryMonitoring";
17 Watcher = new MyFileSystemWatcher(PathToFolder);
18 }
19
21 {
}
22
23
protected override void OnStop()
24
25 {
26 }
}
27
}
28
installutil.exe DirectoryMonitoring.exe
You have now created a service to monitor a directory and you have seen how to debug it.