Click here to Skip to main content
Licence CPOL
First Posted 3 Dec 2008
Views 18,746
Downloads 69
Bookmarked 24 times

Use FileSystemWatcher in a Practical Scenario

By | 3 Dec 2008 | Article
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.

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)

About the Author

interface Mirror

Team Leader

United Arab Emirates United Arab Emirates

Member



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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 2 PinmemberIzzet Kerem Kusmezer3:30 15 Dec '08  
GeneralRe: My vote of 2 Pinmemberinterface Mirror17:06 20 Dec '08  
GeneralMy vote of 2 PinmemberJoe Sonderegger18:55 8 Dec '08  
GeneralRe: My vote of 2 [modified] Pinmemberinterface Mirror17:53 12 Dec '08  
Generalmyblabla [modified] Pinmemberjohannesnestler13:40 4 Dec '08  
GeneralRe: myblabla Pinmemberinterface Mirror17:16 5 Dec '08  
GeneralRe: myblabla Pinmemberjohannesnestler22:16 8 Dec '08  
QuestionCreate file using temp path? Pinmemberichramm4:24 4 Dec '08  
AnswerRe: Create file using temp path? PinmemberAmi Bar9:47 4 Dec '08  
GeneralRe: Create file using temp path? Pinmemberinterface Mirror17:15 5 Dec '08  
GeneralRe: Create file using temp path? Pinmemberinterface Mirror17:48 12 Dec '08  
GeneralRe: Create file using temp path? PinmemberAmi Bar22:04 12 Dec '08  
AnswerRe: Create file using temp path? [modified] Pinmemberinterface Mirror17:04 5 Dec '08  
Hi,
 
You are right. I missed adding +"\\temp.temp" to the end of path.
Also thanks for the suggestion of the replacement. But I think what Ami has suggested is much better way to create temp files. It reduces a lot of headache.
 
Thank you,
 
modified on Friday, December 5, 2008 11:10 PM

Generalvery strange code PinmemberPablo Robert2:47 4 Dec '08  
GeneralRe: very strange code Pinmemberinterface Mirror17:00 5 Dec '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120604.1 | Last Updated 4 Dec 2008
Article Copyright 2008 by interface Mirror
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid