[c#]代码库
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace MonitorDirectory
{
class Program
{
private static FileSystemWatcher FileSystemWatcher1 = null;
private static Hashtable fileTable = new Hashtable();
[STAThread]
public static void Main(string[] args)
{
FolderBrowserDialog dilog = new FolderBrowserDialog();
dilog.Description = "请选择要监视的文件夹";
if(dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
{
string path=dilog.SelectedPath;
FileSystemWatcher1 = new FileSystemWatcher();
FileSystemWatcher1.Path = path;
FileSystemWatcher1.Filter = "*.tmp";
FileSystemWatcher1.IncludeSubdirectories = true;
FileSystemWatcher1.Created += new FileSystemEventHandler(FileSystemWatcher1_Created);
FileSystemWatcher1.Changed += new FileSystemEventHandler(FileSystemWatcher1_Changed);
FileSystemWatcher1.Renamed += new RenamedEventHandler(FileSystemWatcher1_Renamed);
FileSystemWatcher1.EnableRaisingEvents=true;
//加入任务
foreach(string file in Directory.GetFiles(path,"*.txt"))
{
Tasks task = new Tasks();
task.filepathname=file;
task.Push();
}
Tasks t = new Tasks();
Thread th = new Thread(new ThreadStart(t.ThreadWork));
th.Start();
Console.Read();
th.Abort();
FileSystemWatcher1.EnableRaisingEvents = false;
FileSystemWatcher1.Dispose();
FileSystemWatcher1 = null;
return;
}
}
private static void FileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
Monitor.Enter( fileTable.SyncRoot );
try
{
fileTable.Add(e.FullPath,false);
Console.WriteLine("文件"+e.FullPath+"被创建");
}
finally
{
Monitor.Exit( fileTable.SyncRoot );
}
}
private static void FileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{
if(fileTable.ContainsKey(e.FullPath) && !(bool)fileTable[e.FullPath])
{
Monitor.Enter( fileTable.SyncRoot );
try
{
fileTable[e.FullPath]=true;
Console.WriteLine("文件"+e.FullPath+"有数据");
}
finally
{
Monitor.Exit( fileTable.SyncRoot );
}
}
}
private static void FileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
{
if(fileTable.ContainsKey(e.OldFullPath) && (bool)fileTable[e.OldFullPath])
{
Monitor.Enter( fileTable.SyncRoot );
try
{
fileTable.Remove(e.OldFullPath);
Console.WriteLine("文件"+e.FullPath+"被处理");
Tasks task = new Tasks();
task.filepathname=e.FullPath;
task.Push();
}
finally
{
Monitor.Exit( fileTable.SyncRoot );
}
}
}
}
}
[源代码打包下载]