0

I have below code written in C# console app, basically it's watching a folder Temp where it will watch for test.txt file updates.

class Program
{
    private static FileSystemWatcher watcher;
    static void Main(string[] args)
    {
        watcher = new FileSystemWatcher("C:\\Temp\\", "test.txt");
        watcher.Changed += EventCall;
        watcher.EnableRaisingEvents = true;

        Console.ReadKey();
    }

    private static void EventCall(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("update done");
    }
}

When test.txt file updated, EventCall method called 2 times, whats changed needs to be done so that event should called only 1 time?

user584018
  • 10,186
  • 15
  • 74
  • 160
  • Check what files you're getting, for example if I save an excel file, I get 4 events too – BugFinder Feb 27 '19 at 08:45
  • There is No issue while creating file, only 1 time event called, but updated invoke event 2 times. question updated – user584018 Feb 27 '19 at 08:56
  • manually opening, update and closing file, Is this is the issue? – user584018 Feb 27 '19 at 08:58
  • even updating grammatically, event fired 2 times. – user584018 Feb 27 '19 at 08:59
  • 1
    I'm afraid you can't avoid it, [32 people didn't solved the problem](https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice?page=1&tab=votes#tab-top), think about check the last write time. – shingo Feb 27 '19 at 09:10
  • @user584018 Well, if doing an excel file, it seemed to make temp file which while looking in my case for *.xlsx only, it picked up the random.tmp it made, as .xlsx, and so on, hence I said check for the file names. – BugFinder Feb 27 '19 at 09:14

1 Answers1

-1

This below solution is works for me.

private int fireCount = 0;
private void inputFileWatcher_Changed(object sender, FileSystemEventArgs e)
{
   fireCount++;
   if (fireCount == 1)
    {
        MessageBox.Show("Fired only once!!");
        dowork();
    }
    else
    {
        fireCount = 0;
    }
}

}

user584018
  • 10,186
  • 15
  • 74
  • 160