StreamWriter将两个文件附加到现有文件

时间:2017-04-24 13:06:37

标签: c# streamwriter filesystemwatcher

我使用FileSystemWatcher作为服务来跟踪目录中的文件更改。下面的代码将重复的行附加到现有的文本文件 - 我只需要写一行。你能指出为什么吗?

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();
         }
     }
}
}

0 个答案:

没有答案