Thursday, 10 September 2009

C# LoopFileSystemWatcher

This is another implementation of FileSystemWatcher as FileSystemWatcher doesn’t work in all cases.

public class LoopFileSystemWatcher
{
public delegate void LoopFileSystemEventHandler(object source, LoopFileSystemEvent e);
public event LoopFileSystemEventHandler created;

readonly List<string> fileCache = new List<string>();

private readonly string folderPath;
private readonly string fileFilter;
private readonly int checkFrequency;

private bool cancelled = false;

public LoopFileSystemWatcher(string folderPath, string fileFilter, int checkFrequency)
{
this.folderPath = folderPath;
this.fileFilter = fileFilter;
this.checkFrequency = checkFrequency;

DirectoryInfo dir = new DirectoryInfo(folderPath);
foreach (FileInfo file in dir.GetFiles(fileFilter))
{
fileCache.Add(file.Name);
}
}

public void Wait(int waitSeconds)
{
Thread t = new Thread(delegate() { WaitThread(waitSeconds,false); });
t.Start();
}

public FileInfo WaitOnce(int waitSeconds)
{
return WaitThread(waitSeconds,true);
}

private FileInfo WaitThread(int waitSeconds, bool waitOnce)
{
FileInfo lastFile=null;
DirectoryInfo dir = new DirectoryInfo(folderPath);

DateTime future = DateTime.Now.AddSeconds(waitSeconds);
while(DateTime.Now.CompareTo(future)<0)
{
if(cancelled)
{
return null;
}

foreach (FileInfo file in dir.GetFiles(fileFilter))
{
if(!fileCache.Contains(file.Name))
{
fireLoopFileSystemEvent(file);
fileCache.Add(file.Name);
lastFile = file;
if(waitOnce)
{
return file;
}
}
}
Thread.Sleep(checkFrequency * 1000);
}
return lastFile;
}

public void Cancel()
{
this.cancelled = true;
}

private void fireLoopFileSystemEvent(FileInfo file)
{
if (created != null)
{
created(this, new LoopFileSystemEvent(file));
}
}
}

public class LoopFileSystemEvent : EventArgs
{
private readonly FileInfo file;

public LoopFileSystemEvent(FileInfo file)
{
this.file = file;
}

public FileInfo File
{
get { return this.file; }
}
}

No comments:

Post a Comment