0

I am using FileSystemWatcher as a service to track file changes in my directory. This code below appends duplicate lines to an existing text file - I need to write only one line. Could you please point out why?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace RESXWatcher
{
public partial class RESXWatcher : ServiceBase
{
    public RESXWatcher()
    {
        InitializeComponent();
    }

    public void LogEvent(string message)
    {
        string eventSource = "File Monitor Service";
        DateTime dt = new DateTime();
        dt = System.DateTime.UtcNow;
        message = dt.ToLocalTime() + ": " + message;

        EventLog.WriteEntry(eventSource, message);
    }

    FileSystemWatcher myWatcher = new FileSystemWatcher("c:\\platform", 
"*.resx");

    private FileSystemWatcher watcher = null;


    protected override void OnStart(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher("c:\\platform", 
"*.resx");
        watcher.IncludeSubdirectories = true;

        watcher.NotifyFilter = NotifyFilters.LastAccess
                     | NotifyFilters.LastWrite
                     | NotifyFilters.FileName
                     | NotifyFilters.DirectoryName;

         //Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);

        // Begin watching.
        watcher.EnableRaisingEvents = true;
     }

     protected override void OnStop()
     {
        watcher.EnableRaisingEvents = false;
        watcher.Dispose();

        LogEvent("Monitoring Stopped");
     }

     private static void OnChanged(object source, FileSystemEventArgs e)
     {
         WatcherChangeTypes wct = e.ChangeType;
         Console.WriteLine("File {0} {1}", e.FullPath, wct.ToString());

         //Write to text file
         string path = @"c:\Work\RESXWatcherLog.txt";

         if (!File.Exists(path))
         {
             File.Create(path).Dispose();
             using (TextWriter tw = new StreamWriter(path))
             {
                 tw.WriteLine("File {0} was {1}", e.FullPath, 
 wct.ToString());
                 tw.Close();
             }
         }

         else if(File.Exists(path))
         {
                 TextWriter tw = new StreamWriter(path, append: true);
                 tw.WriteLine("\n File {0} {1}", e.FullPath, 
wct.ToString());
                 tw.Close();
         }
     }
}
}
Allan
  • 15
  • 5
  • Id guess maybe your watcher has more than one assignment of the same thing to the onchanged, or, that the file is opened/closed, opened/closed and is firing each time – BugFinder Apr 24 '17 at 13:07
  • IIRC the `OnChanged` event is raised several times with different `FileSustemEventArgs` values. Could yo set a breakpoint in the first line and chech the value of the `e` variable? – Cleptus Apr 24 '17 at 13:12
  • These are the Filters applied and the Watcher Properties assigned to the OnChanged Event. watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; //Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); – Allan Apr 24 '17 at 13:13
  • Could you show us the code that attaches the OnChanged method to the Watcher? – Martin Brown Apr 24 '17 at 13:13
  • @MartinBrown in my previous comment. :) – Allan Apr 24 '17 at 13:16
  • @Allan it would be helpful to have the complete code including the creation of the watcher variable. People around here like to be able to copy and paste into their IDE of choice and test the code. Also it allows us to see subtle things you may have missed. Do you have enough Reputation to edit your post? See http://stackoverflow.com/help/mcve – Martin Brown Apr 24 '17 at 13:24
  • @MartinBrown Attached the full code. – Allan Apr 24 '17 at 13:34
  • You use two different objects with the name `watcher` - the form field and the local in the method. Inside the `OnStop` method you dispose the form field, while local watcher continues to work. – Alexander Petrov Apr 24 '17 at 14:40
  • string[] lines = File.ReadAllLines(path); File.WriteAllLines(path, lines.Distinct().ToArray()); saved me anyway. Thanks all. – Allan Apr 24 '17 at 17:20

0 Answers0