繁体   English   中英

告诉fileSystemWatcher等待

[英]Tell fileSystemWatcher to wait

我有一些写入文件夹的文件,首先写入2个文件,然后10-20分钟后再写入2个文件。

我的问题是:

有什么可能的方式告诉文件系统观察者等待所有4个文件都在文件夹中,然后再执行我的代码?

根据@BugFinder的建议,我创建了类似的内容,但未进行测试。 希望它是有用的:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CustomFileWatcher
{
    public class CustomFileWatcher : IDisposable
    {
        private FileSystemWatcher fileWatcher;
        private IList<string> fileList;
        private IList<string> createdFiles;

        public event EventHandler FilesCreated;
        protected void OnFilesCreated(EventArgs e)
        {
            var handler = FilesCreated;
            if (handler != null)
                handler(this, e);
        }

        public CustomFileWatcher(IList<string> waitForTheseFiles, string path)
        {
            fileList = waitForTheseFiles;
            createdFiles = new List<string>();
            fileWatcher = new FileSystemWatcher(path);
            fileWatcher.Created += fileWatcher_Created;
        }

        void fileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            foreach (var item in fileList)
            {
                if (fileList.Contains(e.Name))
                {
                    if (!createdFiles.Contains(e.Name))
                    {
                        createdFiles.Add(e.Name);
                    }
                }
            }

            if (createdFiles.SequenceEqual(fileList))
                OnFilesCreated(new EventArgs());
        }

        public CustomFileWatcher(IList<string> waitForTheseFiles, string path, string filter)
        {
            fileList = waitForTheseFiles;
            createdFiles = new List<string>();
            fileWatcher = new FileSystemWatcher(path, filter);
            fileWatcher.Created += fileWatcher_Created;
        }

        public void Dispose()
        {
            if (fileWatcher != null)
                fileWatcher.Dispose();
        }
    }
}

用法

class Program
    {
        static void Main(string[] args)
        {
            IList<string> waitForAllTheseFilesToBeCopied = new List<string>();
            waitForAllTheseFilesToBeCopied.Add("File1.txt");
            waitForAllTheseFilesToBeCopied.Add("File2.txt");
            waitForAllTheseFilesToBeCopied.Add("File3.txt");

            string watchPath = @"C:\OutputFolder\";

            CustomFileWatcher customWatcher = new CustomFileWatcher(waitForAllTheseFilesToBeCopied, watchPath);

            customWatcher.FilesCreated += customWatcher_FilesCreated;
        }

        static void customWatcher_FilesCreated(object sender, EventArgs e)
        {
            // All files created.
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM