C#和FileSystemWatcher

如何解决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!");
    }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-