FileSystemWatcher.

P

Peter Kirk

Hi

I am trying to use FileSystemWatcher to watch for changes in a directory.
The problem I am exepriencing is a double firing of an OnChanged event when
a file is opened, edited, and saved. Why is the event fired twice?

Here is my code:

static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"g:\watchme";
watcher.Filter = "";
//watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;
Console.Read();
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnChanged: FullPath=" + e.FullPath + "; Name=" +
e.Name);
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnCreated: FullPath=" + e.FullPath + "; Name=" +
e.Name);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnDeleted: FullPath=" + e.FullPath + "; Name=" +
e.Name);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("OnRenamed: FullPath=" + e.FullPath + "; Name=" + e.Name
+ "; OldFullPath=" + e.OldFullPath + "; OldName=" + e.OldName);
}

Thanks,
Peter
 
I

Ignacio Machin \( .NET/ C# MVP \)

hi,

AFAIK there is no way to avoid this, a Save operation from let's say
notepad triggers more than one events in the OS that each by its own trigger
an event.

you can use several workarounds, like use a timespan and ignore the events
that are closer than a value.

cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top