C# 我能';不要处理文件系统监视程序

C# 我能';不要处理文件系统监视程序,c#,filesystemwatcher,C#,Filesystemwatcher,今天我的问题是,我无法处理fileSystemWatcher(即使是调试)。 所以我想在fileSystemWatcher监视choosen目录时使用函数GetHashFromFile(字符串路径,HashAlgorithm算法)。一旦它在此目录中得到更改(文件已创建、重新命名、更改..),我想使用e.fullPath作为GetHashFromFile中的第一个参数,但它引发了一个异常,即找不到此文件。有人能告诉我应该在代码中的哪个位置使用GetHashFromFile()? 谢谢 下面是我为一

今天我的问题是,我无法处理fileSystemWatcher(即使是调试)。 所以我想在fileSystemWatcher监视choosen目录时使用函数GetHashFromFile(字符串路径,HashAlgorithm算法)。一旦它在此目录中得到更改(文件已创建、重新命名、更改..),我想使用e.fullPath作为GetHashFromFile中的第一个参数,但它引发了一个异常,即找不到此文件。有人能告诉我应该在代码中的哪个位置使用GetHashFromFile()?
谢谢

下面是我为一个不同的应用程序创建的一些示例代码,它正确地使用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;
                }
            }
        }
    }
使用系统;
使用System.Collections.Concurrent;
利用制度全球化;
使用System.Reactive.Linq;
运用系统反思;
使用系统线程;
使用System.Threading.Tasks;
使用System.IO;
使用System.Security.Permissions;
命名空间控制台应用程序9
{
内部课程计划
{
私有静态void Main(字符串[]args)
{
const string directorytowatch=@“d:\junk\watch\”;//要监视新文件的目录
//这将启动文件系统监视器以监视正在创建的新文件
Task.Factory.StartNew(()=>FileSystemMonitor.Instance.WatchDirectory(directorytowatch));
//启动任何新文件的处理
FilesWorker.Instance.ReadQueue();
Console.ReadLine();
}
}
/// 
///“实时”监视文件系统以检查新文件
/// 
[权限集(SecurityAction.Demand,Name=“FullTrust”)]
内部类FileSystemMonitor:SingletonBase
{
专用文件系统监视器()
{
}
内部void WatchDirectory(字符串目录)
{
var watcher=新文件系统监视程序(dir)
{
NotifyFilter=NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.LastAccess,
筛选器=“***”
};
//查看所有文件
watcher.Created+=watcher已创建;
watcher.EnableRaisingEvents=true;
}
已创建专用静态无效监视程序(对象发送方、FileSystemEventArgs FileSystemEventArgs)
{
Console.WriteLine(fileSystemEventTargets.FullPath+“”+fileSystemEventTargets.ChangeType);//用于测试目的
var fileInfo=newfileinfo(fileSystemEventArgs.FullPath);
fileworker.Instance.AddToQueue(fileInfo);
}
}
/// 
///处理要处理的文件队列以及与该队列相关的任务的同步
/// 
内部类FileWorker:SingletonBase
{
私人文件工作者()
{
}
/// 
///仍需要处理的文件队列
/// 
私有只读ConcurrentQueue _filesQueue=新ConcurrentQueue();
/// 
///创建一个信号量,以限制在任何给定时间可以处理文件的线程数
//在这种情况下,在任何给定的时间只允许处理2
/// 
私有静态只读信号量slim信号量=新信号量slim(2,2);
/// 
///将新文件添加到队列
/// 
/// 
内部void AddToQueue(FileInfo FileInfo)
{
_filequeue.Enqueue(fileInfo);
}
/// 
///在给定的时间范围内执行方法
/// 
///要执行的方法
///执行运行之间的时间(秒)
内部void ExecuteMethod(操作方法,双定时器)
{
IObservable observable=可观测间隔(TimeSpan.FromSeconds(timer));
//取消代币
var source=新的CancellationTokenSource();
可观察。订阅(x=>
{
var任务=新任务(方法);
task.Start();
},source.Token);
}
/// 
///获取任何新文件并发送以进行处理
/// 
内部void ReadQueue()
{
//每两秒钟检查一次队列
ExecuteMethod(ProcessQueue,2d);
}
/// 
///从队列中获取文件并开始处理
/// 
内部void ProcessQueue()
{
尝试
{
Semaphore.Wait();
FileInfo FileInfo;
while(_filesque.TryDequeue(out fileInfo))
{
var fileProcessor=新的fileProcessor();
fileProcessor.ProcessFile(fileInfo);
}
}
最后
{
Semaphore.Release();
}
}
}
内部类文件处理器
{
内部无效进程文件(FileInfo FileInfo)
{
//使用该文件执行一些长时间运行的任务
}
}
/// 
///在从它派生的所有类上实现单例模式
/// 
///派生类
公共抽象类SingletonBase,其中T:class
{
公共静态T实例
{
获取{return SingletonFactory.Instance;}
}
/// 
///创建singleton实例的singleton类工厂。
/// 
私家班