Monitor a specified file location for changes
Assume for a moment that you need to monitor a specific folder and its subfolders for incoming files such as a FTP transfer and you wanted to accomplish such a task without an type of action from the system administrator. To accomplish this I will employ the FileSystemWatcher Class which is located in the System.IO NameSpace. First off open Visual Studio 2005 and create a new solution. Next add a new Class Library project to this solution.

Next add a new item to this project and select Windows Service.

Provide a meaningful name, in this case I am using FileMonitor. Once this service is created click “click here to switch to code view”. Add the following using statement:
using System.IO;
Just to confirm the service actually works we will be writing entries to the system event log. Now we need to declare the EventLog object and FileSystemWatcher object that we will consume.
private EventLog _eventLog = null;
private FileSystemWatcher _fileSystemWatcher = null;
Now we are ready to establish the EventLog. What we are going to do is wrap this logic in a method and we will in turn call this method from the OnStart event of our Windows Service.
private void InitializEventLog()
{
string _sourceName = "MyFsoWatcher";
string _logName = "Application";
if (!EventLog.SourceExists(_sourceName))
{
EventLog.CreateEventSource(_sourceName, _logName);
}
_eventLog = new EventLog(); //Create Event Log
_eventLog.Log = _logName; //Assign Event Log Name
_eventLog.Source = _sourceName; //Assign Event Source Name
}
The next step is to create the logic to define the FileSystemWatcher and how we are going to use. Once again I will wrap this logic in a method and initialize it from the OnStart event.
private void IntializeFileSystemWatcher()
{
string _fileStore = "c:\temp";
string _fileType = "*.doc";
try
{
_fileSystemWatcher = new FileSystemWatcher(_fileStore, _fileType);
}
catch (Exception ex)
{
_eventLog.WriteEntry("Problem in IntializeFileSystemWatcher: " + ex.Message.ToString());
}
_fileSystemWatcher.EnableRaisingEvents = true; // Begin watching.
_fileSystemWatcher.IncludeSubdirectories = true; // Monitor Sub Folders
// Add event handlers for doc files and deletion of doc files.
_fileSystemWatcher.Created += new FileSystemEventHandler(OnDocFileCreated);
_fileSystemWatcher.Deleted += new FileSystemEventHandler(OnDocFileDeleted);
}
If you recall I referenced the OnStart event a couple of times. To initialize the event log and file monitor the OnStart Method looks like:
protected override void OnStart(string[] args)
{
InitializEventLog(); //Initialize Event Log
IntializeFileSystemWatcher(); //Initialize The FileSystemWatcher
}
At this point your project should compile and we have established the event log and the FileSystemWatcher will monitor for files that are of type “doc” in the temp folder on the C: drive.
Now it is time to create a installer for this service. Go to the design view of FileMonitor.cs and right click and select “Add Installer”. At this point you will have created ProjectInstaller.cs and you should be looking at the following window:

Bring up the properties of serviceProcessInstaller1 and change the account type to LocalSystem.

Now bring up the properties of serviceInstaller1 and change the StartType to “Automatic”. Also provide a description and display name.

For real world use you would want to modify these service names to provide a unique meaningful name. The last thing to accomplish is to go back to the code view of FileMonitor.cs and wire up the service.
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{
new FileMonitor()
};
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
At this point your service is complete and ready for installation. To install this service open a Visual Studio Command Prompt and change to the folder where your compiled executable resides and execute the following:
installutil -u MyFileSystemWatcher.exe
If all has gone as planned you may now open you services control panel and see this newly installed service.

Go ahead and start the service and place a word document in the c:\temp folder which this service is monitoring and view the results in your event log.
Since there is nothing worse the reinventing the wheel I turned to GotDotNet and looked at the user samples for a tool to allow me to edit a configuration file and to stop and start this service. I found "How To: Write, Modify, Remove, Read Application Settings From Configuration File" by Pankaj Banga which is a Windows Form that provvided the ability to edit a configuration but it did not include the ability to stop and start a service which was easily added. All I did was add two new buttons to the Windows form with the title of "Stop Service" and "Start Service". Here is the code for thos who may be interested.
Private Sub btnStopService_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopService.Click
Dim controller As New ServiceController
controller.MachineName = "."
controller.ServiceName = "FSWService"
Dim status As String = controller.Status.ToString
' Stop the service
controller.Stop()
End Sub
Private Sub BtnStartService_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStartService.Click
Dim controller As New ServiceController
controller.MachineName = "."
controller.ServiceName = "FSWService"
Dim status As String = controller.Status.ToString
' Start the service
controller.Start()
End Sub
Here is a screenshot of the form itself:
