C#和FileSystemWatcher

问题描述

我已经用C#编写了一项服务,该服务应将备份文件(* .bak和* .trn)从数据库服务器移至特殊的备份服务器。到目前为止,效果很好。问题是它尝试将单个文件移动两次。当然这失败了。我已将FileSystemWatcher配置如下:

try
{
    m_objWatcher = new FileSystemWatcher();
    m_objWatcher.Filter = m_strFilter;
    m_objWatcher.Path = m_strSourcepath.Substring(0,m_strSourcepath.Length - 1);
    m_objWatcher.IncludeSubdirectories = m_bolIncludeSubdirectories;
    m_objWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess; // | NotifyFilters.CreationTime;
    m_objWatcher.Changed += new FileSystemEventHandler(objWatcher_OnCreated);
}
catch (Exception ex)
{
    m_objLogger.d(TAG,m_strWatchername + "InitFileWatcher(): " + ex.ToString());
}

监视程序是否可能为同一文件两次生成一个事件?如果我仅将过滤器设置为CreationTime,则它根本不起作用。

如何设置观察者每个文件仅触发一次事件?

预先感谢您的帮助

解决方法

The documentation指出,常见的文件系统操作可能引发多个事件。检查“事件和缓冲区大小”标题下的内容。

常见文件系统操作可能引发多个事件。例如,当文件从一个目录移动到另一个目录时,可能会引发几个OnChanged以及一些OnCreated和OnDeleted事件。移动文件是一个复杂的操作,由多个简单的操作组成,因此会引发多个事件。同样,某些应用程序(例如,防病毒软件)可能会导致FileSystemWatcher检测到其他文件系统事件。

它还提供了一些准则,包括:

将事件处理代码保持尽可能短。

为此,您可以使用FileSystemWatcher.Changed事件将文件排队以进行处理,然后再处理它们。这是一个使用System.Threading.Timer实例处理队列的外观的快速示例。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;

public class ServiceClass
{
    public ServiceClass()
    {
        _processing = false;
        _fileQueue = new ConcurrentQueue<string>();
        _timer = new System.Threading.Timer(ProcessQueue);
        // Schedule the time to run in 5 seconds,then again every 5 seconds.
        _timer.Change(5000,5000);
    }

    private void objWatcher_OnChanged(object sender,FileSystemEventArgs e)
    {
        // Just queue the file to be processed later. If the same file is added multiple
        // times,we'll skip the duplicates when processing the files.
        _fileQueue.Enqueue(e.FilePath);
    }

    private void ProcessQueue(object state)
    {
        if (_processing)
        {
            return;
        }
        _processing = true;
        var failures = new HashSet<string>();
        try
        {
            while (_fileQueue.TryDequeue(out string fileToProcess))
            {
                if (!File.Exists(fileToProcess))
                {
                    // Probably a file that was added multiple times and it was
                    // already processed.
                    continue; 
                }
                var file = new FileInfo(fileToProcess);
                if (FileIsLocked(file))
                {
                    // File is locked. Maybe you got the Changed event,but the file
                    // wasn't done being written.
                    failures.Add(fileToProcess);
                    continue;
                }
                try
                {
                    fileInfo.MoveTo(/*Your destination*/);
                }
                catch (Exception)
                {
                    // File failed to move. Add it to the failures so it can be tried
                    // again.
                    failutes.Add(fileToProcess);
                }
            }
        }
        finally
        {
            // Add any failures back to the queue to try again.
            foreach (var failedFile in failures)
            {
                _fileQueue.Enqueue(failedFile);
            }
            _processing = false;
        }
    }

    private bool IsFileLocked(FileInfo file)
    {
        try
        {
            using (FileStream stream = file.Open(FileMode.Open,FileAccess.Read,FileShare.None))
            {
                stream.Close();
            }
        }
        catch (IOException)
        {
            return true;
        }
        return false;
    }

    private System.Threading.Timer _timer;
    private bool _processing;
    private ConcurrentQueue<string> _fileQueue;
}

在应得的信用额下,我从this answer提取了FileIsLocked

您可能需要考虑的其他事项:

如果您的FileSystemWatcher错过了活动,该怎么办? [文档]确实指出了可能。

请注意,当超出缓冲区大小时,FileSystemWatcher可能会丢失事件。为避免丢失事件,请遵循以下准则:

通过设置InternalBufferSize属性来增加缓冲区大小。

避免观看长文件名的文件,因为长文件名会导致缓冲区满。考虑使用更短的名称重命名这些文件。

使事件处理代码尽可能短。

如果您的服务崩溃了,但是编写备份文件的过程仍在继续写,该怎么办?重新启动服务时,它会拾取并移动这些文件吗?

,

我尝试了各种想法来阻止这种情况。这些事件太靠近了……无法在FileChanged事件中停止。这是我的工作解决方案:

    private System.Timers.Timer timer;
    private FileSystemWatcher fwatcher;

    static void Main(string[] args)
    {
        new Program();
    }

    private Program()
    {
        timer = new System.Timers.Timer(100);
        timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        timer.AutoReset = false; // only once

        fwatcher = new FileSystemWatcher();
        fwatcher.Path = filePath;
        fwatcher.Filter = fileName;
        fwatcher.NotifyFilter = NotifyFilters.LastWrite;
        fwatcher.Changed += new FileSystemEventHandler(FileChanged);
        fwatcher.EnableRaisingEvents = true;

        while (IsRunning)
        {
            Thread.Sleep(100);
        }
        Thread.Sleep(100);
    }
    
    private void FileChanged(object sender,FileSystemEventArgs e)
    {
        timer.Start();
    }

    private void OnTimedEvent(object source,ElapsedEventArgs e)
    {
        Console.WriteLine("file has changed!");
    }

每次更改文件时,计时器只会触发一次。