none
Why ist the event triggered two times? RRS feed

  • Question

  • Hello,

    i don´t know why if i watch a file via last write trigger the event is shooting two times. How can i slove this.

    Here is the code:

    // test.cpp: Hauptprojektdatei.
    
    #include "stdafx.h"
    
    using namespace System;
    using namespace IO;
    
    public ref class Watcher
    {
    private:
    	static void OnChanged( Object^ /*source*/, FileSystemEventArgs^ e )
    	{
    		::String^ ftext;
    		::Boolean eflag;
    		
    		try
    		{
    			do
    			{
    				eflag = false;
    				ftext = ::IO::File::ReadAllText( e->FullPath );
    			}
    			while ( eflag == true);
    		}
    		catch(...)
    		{
    			ftext = "READ ERROR -> TRY AGAIN";
    			eflag = true;
    		}
    		
    		Console::WriteLine( "File: {0} {1}: {2}", e->FullPath, e->ChangeType, ftext);
    	}
    
    	static void OnRenamed( Object^ /*source*/, RenamedEventArgs^ e )
    	{
    		Console::WriteLine( "File: {0} renamed to {1}", e->OldFullPath, e->FullPath );
    	}
    
    public:
    	int static run()
    	{
    	array<String^>^args = System::Environment::GetCommandLineArgs();
    
    	if ( args->Length != 3 )
    	{
    		Console::WriteLine( "Parameter needed: <Directory> <Filter>" );
    		return 0;
    	}
    
    	FileSystemWatcher^ watcher = gcnew FileSystemWatcher;
    	watcher->Path = args[ 1 ];
    	watcher->Filter = args[ 2 ];
    
    	watcher->NotifyFilter = static_cast<NotifyFilters>( NotifyFilters::LastWrite );
    
    	watcher->Changed += gcnew FileSystemEventHandler( Watcher::OnChanged );
    	//watcher->Created += gcnew FileSystemEventHandler( Watcher::OnChanged );
    	//watcher->Deleted += gcnew FileSystemEventHandler( Watcher::OnChanged );
    	//watcher->Renamed += gcnew RenamedEventHandler( Watcher::OnRenamed );
    
    	watcher->EnableRaisingEvents = true;
    
    	// Wait for the user to quit the program.
    	Console::WriteLine( "Press \'q\' to quit the sample." );
    	while ( Console::Read() != 'q' );
    	return 0;
    	}
    };
    
    int main() {
    Watcher::run();
    return 0;
    }

    Sincerly
    Rigoletto
    • Moved by Mathias Schiffer Tuesday, June 23, 2009 1:51 PM English Language Post (From:.NET Framework)
    Tuesday, June 23, 2009 1:33 PM

Answers

  • Hello,

    That's the usual behavior of FileSystemWatcher. I would rename Changed event with Changing.

    To make sure that there will be no more changes to the file by another process, you can try to acquire exclusive access to the file - it will fail if file is still locked and being modified by another process.
    Vitaliy Liptchinsky http://dotnetframeworkplanet.blogspot.com/
    Tuesday, June 23, 2009 2:20 PM