FileSystemWatcher Changed, événement déclenché deux fois
Bonjour,
J'utilise la classe FileSystemWatcher pour analyser le comportement d'un fichier.
Mon problème est que l’événement se déclenche deux fois.
Une solution fonctionne pour moi avec les NotifyFilters,
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
Mais lorsque j'essaye de modifier mon ficher avec notepad pas de problème l'event se déclenche une seule fois, mais avec notepad++ deux fois... WTF? :)
J'ai besoin de faire une appli stable, pouvez vous m'expliquer pourquoi modifier un fichier avec un éditeur différent change quelque chose? Et si cela aura une réelle influence pour mon appli?
Merci d'avance,
Benmaster
Eviter le doublon du FileSystemWatcher !
Merci merci tomlev, ça marche en utilisant un peu ma tete ahah! :mrgreen:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
using System.Security.Permissions;
namespace ConsoleApplicationFileChange
{
class Program
{
static private HashSet<string> _modifiedFiles = new HashSet<string>();
static private System.Timers.Timer _timer;
static void Main(string[] args)
{
// Initialisation du timer
_timer = new System.Timers.Timer
{
Interval = 2000,
AutoReset = false,
};
_timer.Elapsed += _timer_Elapsed;
//
CreateWatcher();
Console.WriteLine("Enter at any time to finish the project");
Console.ReadLine();
}
static public void CreateWatcher()
{
//Create a new FileSystemWatcher.
FileSystemWatcher watcher = new FileSystemWatcher();
//Set the filter to only catch TXT files.
watcher.Filter = "towatch.txt";
//Subscribe to the Created event.
watcher.Changed += new FileSystemEventHandler(watcher_FileChanged);
//Set the path to C:\Temp\
watcher.Path = @"C:\Users\Benoit\Desktop";
//Enable the FileSystemWatcher events.
watcher.EnableRaisingEvents = true;
}
static void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
//A new .TXT file has been created in C:\Temp\
// ajouter à la liste des fichiers modifiés
lock (_modifiedFiles)
{
_modifiedFiles.Add(e.FullPath);
}
// redémarrer le timer
_timer.Stop();
_timer.Start();
}
static void _timer_Elapsed(object sender, EventArgs e)
{
// Copier la liste des fichiers modifiés et la vider
string[] modifiedFiles;
lock(_modifiedFiles)
{
modifiedFiles = _modifiedFiles.ToArray();
_modifiedFiles.Clear();
}
// Traitement des fichiers
//ProcessFiles(modifiedFiles);
Console.WriteLine("A file has been Changed!");
}
}
} |
Bon codage!