Click here to Skip to main content
Click here to Skip to main content

File Watcher Windows Service in C#

By , 1 Sep 2004
 

Introduction

FileSyswatcher is a windows service that monitors a specified path on your disk drive. It will check for all changes to a directory including it's subdirectories and files. The application enables you :

  • To keep check on changes made to directories.
  • Log which user made what changes to which directories and files on what date and time.
  • Generate a HTML report for the daily logs.

FileSysWatcher is written in C# and .Net 1.1. FileSysWatcher will run on all MS Windows platforms that support Windows Services. It's a Windows Service application that uses many powerful features of the .NET platform.

Background

I developed this application to demonstrate how to create a windows service. It also demonstrates the use of the FileSystemWatcher object. It demonstrates how to catch various file change events such as Delete, Create, Rename and Change. Other feature's used are XML, XSLT, FileStream and StreamReader and StreamWriter of the XML and IO namespaces respectively.

Using the code

The application has the following files:
  1. bin\Release\FileSysWatcher.exe.config
  2. bin\Release\logStyles.xsl
  3. App.config
  4. FileSysWatcher.cs
  5. PrintReport.cs
  6. ProjectInstaller.cs
  7. Util.cs bin\Release\FileSysWatcher.exe.config:

This file is generated every time you compile the application. Its a copy of the App.Config file. This is the application configuration file where I have added key-value pairs.

bin\Release\logStyles.xsl:

This is the xsl file which is used to generate the HTML report from the xml.

App.config:

This is the application configuration file where I have added key-value pairs. When application is compiled it generates a file called FileSysWatcher.exe.config which is copied to the bin\Release folder. It contains following values:

  • LOGFILENAME file path where log file is created.
  • ERRORLOGFILENAME file path where errors during execution are logged.
  • PATHTOWATCH the path to monitor.

FileSysWatcher.cs:

This is the actual service file. It has the FileSysWatcher class which inherits from the ServiceBase class. It has methods such as,

  • OnStart()
  • OnStop()

It also hosts the FileSystemWatcher object which exposes the following events,

  • FSWatcher_Changed()
  • FSWatcher_Created()
  • FSWatcher_Deleted()
  • FSWatcher_Renamed()

These events are fired everytime a file/directory is changed, deleted, renamed or created.

PrintReport.cs:

This contains a static Print() method to generate the HTML report.

ProjectInstaller.cs:

This is a ServiceInstaller which is autogenerated. No code has been modified in this class.

Util.cs:

This contains utility methods.

Points of Interest

Some Interesting points:

  • Generating HTML using XML and XSLT.
  • Monitoring File and Directory Activity
  • Installing and UnInstalling a Windows Service.

History

  • First Update : 02nd September 2004.

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

About the Author

Prashant B. Bhide
Web Developer
India India
Member
A Microsoft Certified Professional with over 2 Yrs experience in .Net. Worked on both Windows-based and Web-based Technologies. Used Cutting Edge Tools such as Visual Studio.Net 2003, Oracle9i. Worked with organisations such as Cygnus Software Pvt. Ltd. and Deloitte Consulting. Presently working with Nihilent Technologies Pvt. Ltd., Pune, India as System Analyst.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberLavrekho15 Dec '12 - 4:23 
-
Suggestionsource code is damagedmemberAnand Priyadarshi27 Nov '12 - 21:14 
whilw extracting with winrar it is giving error file is damaged or in unknown format
QuestionEvent not Firingmembermichmsk19 Jan '12 - 2:55 
I built a windows service using FileWatcher object, however, I am monitoring for creation files on a window server 2003, when the file is created in the folder, the services is not picking it up after some hours. I made sure that the user account is running has full rights on the network folde. I don't understand why this is happening, becuase when i restart the service it works again. Which means the service only works for limited time.
by
Mike zuluboy Maseko
"dont try to be someone because everyone is taken"

GeneralMy vote of 4membertusharpal17 Jul '11 - 18:51 
Nice Article....
GeneralFile watcher results appended to a .csv filememberstacson2 Nov '10 - 8:41 
Hi there,
 
I would like to append to a .csv file the details from the file system watcher. So when the folder I am watching gets updated I would like the file name, the event (created, deleted etc), date and time to be logged in a .csv file.
 
Can anyone help me with this? My file system watcher is running from a console app and is working I just don't know how to get the details in a .csv file.
 
Cheers Smile | :)
 
static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            Console.WriteLine("FileSystemWatcher Started....");
            watcher.Path = @"C:\Uploader\TransientStorage";
            watcher.IncludeSubdirectories = false;
            watcher.Filter = "*.jpg";
 
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            watcher.EnableRaisingEvents = true;
 
            Console.WriteLine(@"Press 'q' to quit app.");
            while (Console.Read() != 'q') ;
        }
        
        private static void OnChanged(object source, FileSystemEventArgs e) 
        {
        Console.WriteLine("File: {0} {1}!", e.Name, "has been " + e.ChangeType);
        }
 
        private static void OnRenamed(object source, RenamedEventArgs e) 
        {
            Console.WriteLine("File: {0} renamed to\n{1}", e.Name, e.ChangeType);
        }

GeneralMy vote of 3memberbonypatel9 Aug '10 - 3:43 
Good Post, It realy helpful for basic window services as wel as FileWatcher use.
Thank You
QuestionDisplay UsernamememberHolger_0130 Jun '08 - 6:45 
I have also only see the User System. Can anybody help me to display the username how have delete or change any files.
And what must i do to dont display delete *.tmp or other temporär Files
 
Thanks Holger
Generalreportmemberarkiboys25 Jun '08 - 1:47 
Hi,
How do I create the report?
Thanks
GeneralRe: reportmemberarkiboys25 Jun '08 - 2:11 
I added a simple win form project with a button.
Added a reference to FileSysWatcher service.
In the button click event I have:
 
PrintReport.Print();
The problem:
 
I can not get past this line:
string logFilePath = Util.GetSetting("LOGFILENAME");
Any thoughts?
Thanks
GeneralService Immediately StopsmemberC1iff13 Mar '08 - 9:36 
Whenever I start the service it stops with an IO Exception. The Service's ErrorLogFile file cannot be accessed because the Service is using it?
 
Service cannot be started. System.IO.IOException: The process cannot access the file 'C:\FileSysWatcher\ErrorLogFile\Log.txt' because it is being used by another process.
at FileSysWatcher.Util.WriteToErrorLogFile(Exception sourceException)
at FileSysWatcher.FileSysWatcher.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
 
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 2 Sep 2004
Article Copyright 2004 by Prashant B. Bhide
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid