File System Monitoring Using Windows Service

In this article, I discuss about how to monitor file system to keep track of creation, deletion, updation and renaming of files in a folder in the file system.

First we will understand how to monitor a folder for changes using FileSystemWatcher class, which is provided by .NET library. Then we will convert this program to a Windows Service to run in the background. We will also discuss about how to install service, start and stop it.

Using FileSystemWatcher Class

This class provide by .NET library is used to monitor changes in a folder, optionally including its sub directories. In order to use this class follow the steps given below: The following program shows how to display a message when a file is created or deleted from c:\ folder.
  1. Create a new Console Application using Visual Studio.NET 2005
  2. Create a class with the name FileSytemMonitor and place the following code in it.
    Imports System.IO
    
    Public Class FileSystemMonitor
    
        Public Shared Sub Main()
            Dim fsw As New FileSystemWatcher()  ' create an object of FileSystemWatcher
    
            ' set properties of FileSystemWatcher object
            fsw.Path = "c:\"
            fsw.IncludeSubdirectories = True
    
            ' add event handlers 
            AddHandler fsw.Created, New FileSystemEventHandler(AddressOf File_Created)
            AddHandler fsw.Deleted, New FileSystemEventHandler(AddressOf File_Deleted)
            
            fsw.EnableRaisingEvents = True  ' enable monitoring
            
            Console.WriteLine("Started Monitoring C:\ folder. Press enter key to stop.")
            Console.ReadLine()
    
        End Sub
    
        ' event handler to handle created event 
        Public Shared Sub File_Created(ByVal obj As Object, ByVal e As FileSystemEventArgs)
            Console.WriteLine(e.FullPath & " - Created")
        End Sub
    
        ' event handler to handle deleted event 
        Public Shared Sub File_Deleted(ByVal obj As Object, ByVal e As FileSystemEventArgs)
            Console.WriteLine(e.FullPath & " - Deleted")
        End Sub
    
    End Class
    
    
  3. Change start up object of the project to FileSystemMonitor class.
  4. Run the project using F5.
  5. Make some changes to C:\ folder and see what messages are displayed in your console.
  6. Press Enter key to stop monitoring.

Creating a Windows Service To Monitor File System

Now let us build a Windows Service to monitor file system. A Windows Service is program that runs in the background and perform its operations without any user interaction. Our file monitoring application is a good candidate for Windows service.

A windows service can be installed, uninstalled using a utility - InstallUtil.Exe - provided by .NET.

Once a windows service is installed, it can be managed - stared, stopped etc. - using Services program provided by Windows.

Let us now take steps to create a windows service to monitor a folder provided by user at the time of configuring service. If user doesn't provide folder name then we use c:\ as the default folder. We write a line of text with date , time , filename and operation in a text file with the name FileSystem.Log that is placed in temp directory of Windows OS.
  1. Start Visual Studio.NET 2005
  2. Select File->New Project
  3. Expand Visual Basic node and select Windows as Project type.
  4. Select Windows Service as the template.
  5. Enter FSMonitor as the project name and select the folder where you want to place the project.
  6. You get Service1.vb[Design].
  7. Click on link click here to switch to code view to get into code view - service1.vb.
  8. Modify the code as follows.
    
    Imports System.IO
    Public Class Service1
    
        Dim fsw As FileSystemWatcher
        Dim fw As StreamWriter
    
        Protected Overrides Sub OnStart(ByVal args() As String)
            fw = New StreamWriter(Environment.GetEnvironmentVariable("temp") & "\filesystem.log")
            fsw = New FileSystemWatcher()
    
            If args.Length > 0 Then
                fsw.Path = args(0)
                fsw.IncludeSubdirectories = True
            Else  ' default settings
                fsw.Path = "c:\"
                fsw.IncludeSubdirectories = False
            End If
    
            AddHandler fsw.Created, New FileSystemEventHandler(AddressOf File_Created)
            AddHandler fsw.Deleted, New FileSystemEventHandler(AddressOf File_Deleted)
            fsw.EnableRaisingEvents = True
    
        End Sub
    
        Public Sub File_Created(ByVal obj As Object, ByVal e As FileSystemEventArgs)
            fw.WriteLine(Now.ToShortDateString & " " & Now.ToShortTimeString & " - " & e.FullPath & " - Created")
        End Sub
    
        Public Sub File_Deleted(ByVal obj As Object, ByVal e As FileSystemEventArgs)
            fw.WriteLine(Now.ToShortDateString & " " & Now.ToShortTimeString & " - " & e.FullPath & " - Deleted")
        End Sub
    
        Protected Overrides Sub OnStop()
            fw.Close()
        End Sub
    
    End Class
    
    
  9. Go to Designer, right click and select Add Installer option from popup menu.
  10. Visual Studio creates two components - ServiceProcessInstaller1 and ServiceInstaller1
  11. Select ServiceInstaller1 and change following properties
     
     ServiceName : FSMonitor
     DispalyName : File System Monitor
     StartType   : Manual (default)
      
  12. Select ServiceProcessInstaller1 and change following properties
     
      Account : LocalSystem
      
  13. Go to solution explorer and build the project to create .exe  (FSMonitor.exe) file for the project
  14. Go to command prompt using Microsoft Visual Stdio.2005 -> Visual Studio Tools -> Visual Studio.NET 2005 Command Prompt
  15. Go to the directory where FSMonitor.exe is present ( debug directory under bin directory)
  16. Enter the following command to install service
    Installutil  FSMonitor.exe
    
  17. If installation is successful, you must see File System Monitor service in the list of Services in Windows. You can invoke services program using Control Panel -> Performance and Maintenance -> Administrative tools -> Services
  18. Go to File System Monitor service and select Properties from popup menu (right button)
  19. \
  20. Select General tab in Properties and enter the full path of the folder that you want to monitor in Start Parameters textbox
  21. Click on Start button to start service
  22. Add and delete some files in the path specified for service. You must see a few lines related to the changes in FileSystem.Log file in temp directory (ex: d:\windows\temp)
  23. You can stop service using Service program using Stop option from popup menu of the service.
  24. You can uninstall service by giving the following command at command prompt
     InstallUtil /u FSMonitor.exe
     
That's all we have to do. You can think of making necessary changing according to your requirement. For example, you can modify rows in the table as and when files in a folder are changed. For example, you can delete and insert rows as files are deleted and created.

Try this program and Send me feedback , if you have any.

Keep coding,
Srikanth.