c# - 我无法处理 fileSystemWatcher

标签 c# filesystemwatcher

今天我的问题是我无法处理 fileSystemWatcher(即使有调试)。 所以...我想在 fileSystemWatcher 监视所选目录时使用函数 GetHashFromFile(string path, HashAlgorithm algorithm )。一旦它在此目录中发生更改(文件已创建、重命名、更改..),我想将 e.fullPath 用作 GetHashFromFile 中的第一个参数,但它抛出一个异常,因为该文件不能成立。有人可以告诉我应该在代码中的哪个位置使用 GetHashFromFile() 吗? 谢谢 !

最佳答案

这是我为不同的 SO question 创建的一些示例代码它正确地使用 FileSystemWatcher 来处理应该满足您需要的文件

    using System;
    using System.Collections.Concurrent;
    using System.Globalization;
    using System.Reactive.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    using System.IO;
    using System.Security.Permissions;


    namespace ConsoleApplication9
    {
        internal class Program
        {

            private static void Main(string[] args)
            {


                const string directorytowatch = @"d:\junk\watch\"; // the directory to watch for new files
                // this initiates a filesystemmonitor to watch for new files being created 
                Task.Factory.StartNew(() => FileSystemMonitor.Instance.WatchDirectory(directorytowatch));

                // initiate the processing of any new files
                FilesWorker.Instance.ReadQueue();
                Console.ReadLine();

            }


        }

        /// <summary>
        /// Monitors the filesystem in "real-time" to check for new files
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        internal class FileSystemMonitor : SingletonBase<FileSystemMonitor>
        {
            private FileSystemMonitor()
            {
            }

            internal void WatchDirectory(string dir)
            {
                var watcher = new FileSystemWatcher(dir)
                {
                    NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.LastAccess,
                    Filter = "*.*"
                };

                // watch all files
                watcher.Created += WatcherOnCreated;
                watcher.EnableRaisingEvents = true;
            }

            private static void WatcherOnCreated(object sender, FileSystemEventArgs fileSystemEventArgs)
            {
                Console.WriteLine(fileSystemEventArgs.FullPath + "" + fileSystemEventArgs.ChangeType); // for test purposes
                var fileInfo = new FileInfo(fileSystemEventArgs.FullPath);
                FilesWorker.Instance.AddToQueue(fileInfo);
            }
        }

        /// <summary>
        /// handles the queue of files to be processed and the syncronisation of tasks related to the queue
        /// </summary>
        internal class FilesWorker : SingletonBase<FilesWorker>
        {
            private FilesWorker()
            {
            }

            /// <summary>
            /// The queue of files which still need to be processed
            /// </summary>
            private readonly ConcurrentQueue<FileInfo> _filesQueue = new ConcurrentQueue<FileInfo>();

            /// <summary>
            /// create a semaphore to limit the number of threads which can process a file at any given time
            // In this case only allow 2 to be processed at any given time
            /// </summary>
            private static readonly SemaphoreSlim Semaphore = new SemaphoreSlim(2, 2);

            /// <summary>
            /// add new file to the queue
            /// </summary>
            /// <param name="fileInfo"></param>
            internal void AddToQueue(FileInfo fileInfo)
            {
                _filesQueue.Enqueue(fileInfo);
            }

            /// <summary>
            /// executes a method on a given timeframe
            /// </summary>
            /// <param name="method">method to execute</param>
            /// <param name="timer">time between execution runs (seconds)</param>
            internal void ExecuteMethod(Action method, double timer)
            {
                IObservable<long> observable = Observable.Interval(TimeSpan.FromSeconds(timer));
                // Token for cancelation
                var source = new CancellationTokenSource();

                observable.Subscribe(x =>
                {
                    var task = new Task(method);
                    task.Start();
                }, source.Token);

            }

            /// <summary>
            /// Get any new files and send for processing
            /// </summary>
            internal void ReadQueue()
            {
                // check the queue every two seconds
                ExecuteMethod(ProcessQueue, 2d);
            }

            /// <summary>
            /// takes files from the queue and starts processing
            /// </summary>
            internal void ProcessQueue()
            {
                try
                {
                    Semaphore.Wait();
                    FileInfo fileInfo;
                    while (_filesQueue.TryDequeue(out fileInfo))
                    {
                        var fileProcessor = new FileProcessor();
                        fileProcessor.ProcessFile(fileInfo);
                    }
                }
                finally
                {
                    Semaphore.Release();
                }
            }

        }

        internal class FileProcessor
        {
            internal void ProcessFile(FileInfo fileInfo)
            {
                // do some long running tasks with the file
            }
        }


        /// <summary>
        /// Implements singleton pattern on all classes which derive from it
        /// </summary>
        /// <typeparam name="T">Derived class</typeparam>
        public abstract class SingletonBase<T> where T : class
        {

            public static T Instance
            {
                get { return SingletonFactory.Instance; }
            }

            /// <summary>
            /// The singleton class factory to create the singleton instance.
            /// </summary>
            private class SingletonFactory
            {

                static SingletonFactory()
                {
                }

                private SingletonFactory()
                {
                }

                internal static readonly T Instance = GetInstance();

                private static T GetInstance()
                {
                    var theType = typeof(T);
                    T inst;
                    try
                    {
                        inst = (T)theType
                            .InvokeMember(theType.Name,
                                BindingFlags.CreateInstance | BindingFlags.Instance
                                | BindingFlags.NonPublic,
                                null, null, null,
                                CultureInfo.InvariantCulture);
                    }
                    catch (MissingMethodException ex)
                    {
                        var exception = new TypeLoadException(string.Format(
                            CultureInfo.CurrentCulture,
                            "The type '{0}' must have a private constructor to " +
                            "be used in the Singleton pattern.", theType.FullName)
                            , ex);
                        //LogManager.LogException(LogManager.EventIdInternal, exception, "error in instantiating the singleton");
                        throw exception;
                    }

                    return inst;
                }
            }
        }
    }

关于c# - 我无法处理 fileSystemWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32269811/

相关文章:

c# - 用空字符串替换的正则表达式

c# - POST 后出现 NullReferenceException

c# - 如何检查目录 1 是否是 dir2 的子目录,反之亦然

powershell - FileSystemWatcher检测何时将文件 move 到文件夹

cocoa - 在沙盒应用程序中使用 FSEvents

c# - 为什么即使使用 Monitor 时,并非所有成员变量都需要 volatile 以保证线程安全? (为什么这个模型真的有效?)

c# - FileSystemWatcher 是否创建自己的线程?

c# - FileSystemWatcher 和最后一行文本文件

c# - C# 中带有 FileSystemWatcher 的 Windows 服务

c# - Azure 服务总线 SubscriptionClient 高延迟/无法同时接收消息