using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.IO; ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace Demo
{
public class FileListen
{
private AutoResetEvent autoResetEvent;
private string listenPath = @"D:\項目資料\隨筆\Demo\listen";
private Queue fileQueue = new Queue();
private static object objLock = new object();
private bool isWait = true;
public FileListen(string listenPath)
{
this.listenPath = listenPath;
Init();
}
private void Init()
{
FileSystemWatcher watcher = new FileSystemWatcher(listenPath);
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler(MonitorFileCreate);
autoResetEvent = new AutoResetEvent(false);
Thread thread = new Thread(DoWork);
thread.Start();
Reload();
}
private void Reload()
{
DirectoryInfo dires = new DirectoryInfo(listenPath);
FileInfo[] files = dires.GetFiles().OrderBy(c => c.CreationTime).ToArray();
foreach (FileInfo file in files)
{
if (!fileQueue.Contains(file.FullName))
{
fileQueue.Enqueue(file.FullName);
//休眠1秒
Thread.Sleep(1000);
autoResetEvent.Set();
}
}
}
private void DoWork()
{
Console.WriteLine("DoWork Begin");
//等待信號
while (isWait)
{
autoResetEvent.WaitOne();
//鎖定 防止併發
lock (objLock)
{
//獲取文件隊列信息 並移除
string path = fileQueue.Dequeue().ToString();
Console.WriteLine("正在處理=>" + path);
Console.WriteLine("處理中...");
Console.WriteLine("處理完成");
File.Delete(path);
}
}
}
private void MonitorFileCreate(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
try
{
if (!fileQueue.Contains(e.FullPath))
{
Console.WriteLine("監聽文件=>" + e.FullPath);
fileQueue.Enqueue(e.FullPath);
autoResetEvent.Set();
}
}
catch (Exception ex)
{
//LogHelper.Error(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
}