You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
3.4 KiB
C#

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileDataUpload.FileOperate
{
public sealed class MonitorEngine
{
public string Path;
public string Filter;
public delegate void FindOneFile(string path);
public event FindOneFile FindOneFileEvent;
private FileSystemWatcher watcher = new FileSystemWatcher();
private static readonly Lazy<MonitorEngine> lazy = new Lazy<MonitorEngine>(() => new MonitorEngine());
public static MonitorEngine Instance
{
get
{
return lazy.Value;
}
}
public MonitorEngine()
{
watcher.Changed += new FileSystemEventHandler(OnProcess);
watcher.Created += new FileSystemEventHandler(OnProcess);
watcher.Deleted += new FileSystemEventHandler(OnProcess);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
}
/// <summary>
/// 监控文件夹
/// </summary>
/// <param name="path"></param>
/// <param name="filter"></param>
public void WatcherStrat()
{
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
}
watcher.Path = Path;
watcher.Filter = Filter;
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectories = true;
}
public void WatcherStop()
{
watcher.EnableRaisingEvents = false;
watcher.IncludeSubdirectories = false;
}
private void OnProcess(object source, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
OnCreated(source, e);
}
else if (e.ChangeType == WatcherChangeTypes.Changed)
{
OnChanged(source, e);
}
else if (e.ChangeType == WatcherChangeTypes.Deleted)
{
OnDeleted(source, e);
}
}
private void OnCreated(object source, FileSystemEventArgs e)
{
string TempFilePath = e.FullPath;
if (FindOneFileEvent != null)
{
FindOneFileEvent(TempFilePath);
}
//Console.WriteLine("文件新建事件处理逻辑 {0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name);
}
private void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("文件改变事件处理逻辑{0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name);
}
private void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("文件删除事件处理逻辑{0}  {1}   {2}", e.ChangeType, e.FullPath, e.Name);
}
private void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("文件重命名事件处理逻辑{0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name);
}
}
}