了解FileSystemWatcher

时间:2016-02-25 09:21:34

标签: c# .net io filesystems filesystemwatcher

我编写了一个简单的示例程序,它应该将数据写入文件并在有数据时实时读取。我写这段代码:

using System;
using System.IO;
using System.Reflection;
using System.Threading;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            const string file = "sample.txt";

            var thread = new Thread(() =>
                                    {
                                        var r = new Random();
                                        using (var sw = new StreamWriter(new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) {AutoFlush = true})
                                        {
                                            while (true)
                                            {
                                                Thread.Sleep(r.Next(100, 500));
                                                sw.WriteLine(DateTime.Now);
                                            }
                                        }
                                    });
            thread.Start();

            using (var watcher = new FileSystemWatcher
                                 {
                                     Path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                     Filter = file,
                                     NotifyFilter = NotifyFilters.LastWrite
                                 })
            {
                var mse = new ManualResetEventSlim(false);
                watcher.Changed += (sender, eventArgs) => 
                    mse.Set();
                watcher.EnableRaisingEvents = true;
                using (var sr = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)))
                {
                    while (true)
                    {
                        mse.Wait();
                        ProcessData(sr.ReadToEnd());
                        mse.Reset();
                    }
                }
            }

        }

        private static void ProcessData(string s)
        {
            Console.WriteLine(s);
        }
    }
}

但似乎watcher仅在文件打开时有效,但在填充信息时却不起作用(即使在AutoFlush上启用了StreamWriter标志)。数据实际位于磁盘上,但观察者不会引发事件File changed

我只想在写入数据时避免无限循环和处理数据。

1 个答案:

答案 0 :(得分:0)

如果你不关闭它们,我认为你应该将FileStreamStreamWriter分别放在using条款中来处置它们:

string file = "sample.txt";
using (var fs =new FileStream(file, FileMode.Create, 
                                    FileAccess.ReadWrite, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs) {AutoFlush = true})
{
    ..
    ..
}

在直接关闭或通过处置关闭之前,系统不会通知文件系统已完成更改。否则你会被变化的事件所淹没..