如何在C#中编写文件系统监视器?

4
我用C#编写了一个小应用程序,其中使用FileSystemWatcher监视特定文件夹。一旦文件被更新,它就会打开串口并将文件的内容写到串口中。但有时文件不会在4-5个小时内更新。看起来FileSystemWatcher休眠了,并且在文件更新后没有响应。
以下是我的代码:
FileSystemWatcher watcher = new FileSystemWatcher();

watcher.Path = @"Z:\";
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.LastAccess;

watcher.Filter = "*.wsx";
watcher.Changed += new FileSystemEventHandler(OnChanged);

Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;

public static string CrL = "\r\n";

private static void OnChanged(object source, FileSystemEventArgs e)
{
    string FileName;
    FileName = e.FullPath;

    Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
    Console.WriteLine("FILE is changed 1");
    SerialPort port = new SerialPort("COM1");

    port.Encoding = Encoding.ASCII;
    port.Open();

    using (System.IO.TextReader reader = System.IO.File.OpenText(e.FullPath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            port.Write(line);
            port.Write(CrL);
        }
    }

    port.Close();

    Console.WriteLine("FILE is sent to com port");
}

任何建议吗?

1
你应该加入错误处理并查看是否发生了什么:watcher.Error += new ErrorEventHandler(WatcherError); - mathieu
虽然不确定这个评论是否适用于你的问题,但无论如何:“尽管EnableRaisingEvents后来被框架代码设置为true,但也会有一个内部标志runOnce,最终导致WaitForChanged()仅等待第一次更改通知(这可能是指指定目录中的所有更改通知而不仅仅是与FileSystemWatcher.Filter匹配的文件通知)。由于runOnce标志被内部设置,因此FileSystemWatcher在收到第一条潜在的不需要的通知后便“停止侦听”。" - Christian
以上评论可在此处找到:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx - Christian
@Christian:如果文件定期更改,则上述代码可以正常工作。但是,如果等待时间过长,比如说超过4-5个小时,那么它就不会触发。 - user726720
@Mathieu:是的,我认为我应该这样做。我会加入一些错误处理并观察情况如何发展。 - user726720
2个回答

0
如果在dotnet中出现导致FileSystemWatcher“超时”的问题,一个快速的解决方法是使用计时器控件并定期重新初始化FileSystemWatcher,以避免其“超时”。您可以访问dotnet调试符号服务器,因此也可以自行调试FileSystemWatcher以查看其操作。

0
也许FSW对象正在被垃圾回收,因为它超出了范围。
在您上面的代码中,您没有显示您在哪里定义“watcher”对象。
如果它是在您使用它的同一个方法中定义的,也许这就是问题所在。尝试在类的顶部定义它(在任何方法之外)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接