Click here to Skip to main content
15,891,529 members
Articles / Programming Languages / C#
Article

Use FileSystemWatcher in a Practical Scenario

Rate me:
Please Sign up or sign in to vote.
3.20/5 (9 votes)
3 Dec 2008CPOL2 min read 43.2K   238   26   16
Use FileSystemWatcher in a practical scenario

Introduction

With the speed with which technology moves ahead and companies release new versions of their programming languages and frameworks, it has been too difficult to focus on everything in a platform and be a master of everything. This expansion in technology has one more consequence and that is, you will find everything about new technologies since the developers are focusing more on them. But if you want to develop a program with some basic system level functionalities, you may find it difficult to find code snippets or tools to shorten your development time or even guidelines about how to do what you want.

But no matter how fast development platforms expand, the necessity of using basic classes or programming approaches is never lost. One class amongst these classes which is very interesting to use is the FileSystemWatcher class. In this article, I am not going to teach you how to use this class. You can find a lot of articles on the Internet explaining how to use this class or the kind of errors people get while using this class.

Background

In this article, I am going to show you my solution to a very simple problem that you may need to solve. I hope that if you have the same problem, this code snippet can be useful to you.

I have a client server application communicating with each other using port 2000. The client application gets the data from Server and processes it and at the same time it writes the log to the file for debugging purpose. Last week I got a new requirement to develop an application to monitor the log file and get the latest change from the last change and process it with some business logic. For example if AAAA; BBBB; CCCC (where “;” is a separator between different packets) is in the file and CCCC is the latest packet received from server, my new application should read CCCC and process it.

Using the Code

The solution I came up with is to use a temporary file that acts as a container for the latest data. Whenever log is added to the log file, I read the complete log file and temp files and compare them. After getting the difference which is the new packet, I write the changes to the temp file so that both log file and change file be exactly the same so that next time I can compare the temp file with log file. It is obvious that after getting the data and logging it into log file, size of the log file is bigger than the temp file and I can compare and get the difference.

C#
static void Main ( string [ ] args )
{
    string path = @"c:\Test";
    // I have used filter (WatchTest.Log) to watch only "WatchTest.Log" .
    FileSystemWatcher watch = new FileSystemWatcher ( path , "WatchTest.Log" );
    watch.Changed += new FileSystemEventHandler ( watch_Changed );
    watch.EnableRaisingEvents = true;

    Console.ReadLine( );
}

void watch_Changed ( object sender , FileSystemEventArgs e )
{
    // I Prefer to create the temp file in TEMP directory 
    // so I don't have any Permission problem anywhere
    string tempPath = System.Environment.GetEnvironmentVariables ( ) 
                      [ "TEMP" ].ToString ( )+"\\Log.temp";

    // If temp file is not there, create it.
    if ( !File.Exists ( tempPath ) )
    {
        File.Create( tempPath );
    }
    // Read the temp file and store the result in memory
    string temp = File.ReadAllText( tempPath );
    string difference = string.Empty;

    // Read newly changed file from Memory
    string path = e.FullPath;
    StreamReader reader = new StreamReader( path );
    string content = reader.ReadToEnd( );
    reader.Close( );

    // Compare the File in Memory with the temp file and get the difference
    if ( content.Length > temp.Length ) // This means that File has increased in size.
    {
        if ( temp.Length > 0 )
        {
            // Replacing the old content with "" to get only the difference
            difference = content.Replace( temp , "" );
        }
        else
        {
            difference = content;
        }
        // Write all the new content back to Temp file for future comparisons.
        File.WriteAllText( tempPath , content );
    }
    else
    {
        // Write all the new content back to Temp file for future comparisons.
        File.WriteAllText( tempPath , content );
    }
            
    // Process the latest data (stored in destination) 
}

References

History

  • 4th December, 2008: Initial post
    This is version 1.0 of this code snippet. I will be updating this if I learn about what else can be added to this snippet to make it more useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
United Arab Emirates United Arab Emirates
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
suramrit3-Feb-13 18:25
suramrit3-Feb-13 18:25 
GeneralMy vote of 2 Pin
Izzet Kerem Kusmezer15-Dec-08 3:30
Izzet Kerem Kusmezer15-Dec-08 3:30 
GeneralRe: My vote of 2 Pin
interface Mirror20-Dec-08 17:06
interface Mirror20-Dec-08 17:06 
GeneralMy vote of 2 Pin
Joe Sonderegger8-Dec-08 18:55
Joe Sonderegger8-Dec-08 18:55 
what's new?
GeneralRe: My vote of 2 [modified] Pin
interface Mirror12-Dec-08 17:53
interface Mirror12-Dec-08 17:53 
Generalmyblabla [modified] Pin
johannesnestler4-Dec-08 13:40
johannesnestler4-Dec-08 13:40 
GeneralRe: myblabla Pin
interface Mirror5-Dec-08 17:16
interface Mirror5-Dec-08 17:16 
GeneralRe: myblabla Pin
johannesnestler8-Dec-08 22:16
johannesnestler8-Dec-08 22:16 
QuestionCreate file using temp path? Pin
User 43300284-Dec-08 4:24
User 43300284-Dec-08 4:24 
AnswerRe: Create file using temp path? Pin
Ami Bar4-Dec-08 9:47
Ami Bar4-Dec-08 9:47 
GeneralRe: Create file using temp path? Pin
interface Mirror5-Dec-08 17:15
interface Mirror5-Dec-08 17:15 
GeneralRe: Create file using temp path? Pin
interface Mirror12-Dec-08 17:48
interface Mirror12-Dec-08 17:48 
GeneralRe: Create file using temp path? Pin
Ami Bar12-Dec-08 22:04
Ami Bar12-Dec-08 22:04 
AnswerRe: Create file using temp path? [modified] Pin
interface Mirror5-Dec-08 17:04
interface Mirror5-Dec-08 17:04 
Generalvery strange code Pin
Pablo Robert4-Dec-08 2:47
Pablo Robert4-Dec-08 2:47 
GeneralRe: very strange code Pin
interface Mirror5-Dec-08 17:00
interface Mirror5-Dec-08 17:00 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.