Event watcher

  • Thread starter Thread starter Priya Bange
  • Start date Start date
P

Priya Bange

Guest
Hi Experts,

I have an event watcher running on topshelf windows service. The event watcher works as expected ,on start up it tries to process existing files in the folder & then wait for the new one.

Am facing the following listed issues

1. Not processing all the files on startup at times.

2. The existing process method is called on startup how can I call the same method safely again repetitively to process the files which didn't got cached for processing.



Please find the code block below for reference and am just new to C# so exact reference guidance is highly supportive. I tried playing with sliding with increasing duration still it didn't helped.

class FileWatch
{
private static MemoryCache FilesToProcess = MemoryCache.Default;
private FileSystemWatcher inputFileWatcher;

public bool Start()
{

var directoryToWatch = @"Some directory path";


ProcessExistingFiles(directoryToWatch);

inputFileWatcher = new FileSystemWatcher(directoryToWatch);

inputFileWatcher.IncludeSubdirectories = true;
inputFileWatcher.InternalBufferSize = 32768; // 32 KB
inputFileWatcher.Filter = "*.*";
inputFileWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Attributes;

inputFileWatcher.Created += FileCreated;
inputFileWatcher.Changed += FileChanged;
inputFileWatcher.Error += WatcherError;

inputFileWatcher.EnableRaisingEvents = true;


return true;

}



public bool Stop()
{
inputFileWatcher.Dispose();

return true;
}


private void ProcessExistingFiles(string inputDirectory)
{

foreach (var filePath in Directory.EnumerateFiles(inputDirectory, "*.*", SearchOption.AllDirectories))
{
AddToCache(filePath);
}
}

private void FileCreated(object sender, FileSystemEventArgs e)
{

if (!IsReadOnly(e.FullPath))
{
AddToCache(e.FullPath);
}
}

private void FileChanged(object sender, FileSystemEventArgs e)
{

if (!IsReadOnly(e.FullPath))
{
AddToCache(e.FullPath);
}
}



private void WatcherError(object sender, ErrorEventArgs e)
{
ProcessExistingFiles(@"Some directory path");
}

private void AddToCache(string fullPath)
{
var item = new CacheItem(fullPath, fullPath);

var policy = new CacheItemPolicy
{
RemovedCallback = ProcessFile,
SlidingExpiration = TimeSpan.FromSeconds(2),
};

FilesToProcess.Add(item, policy);
}

private void ProcessFile(CacheEntryRemovedArguments args)
{

if (args.RemovedReason == CacheEntryRemovedReason.Expired)
{
Process(args.CacheItem.Key);
}
else
{
}
}

private static bool IsReadOnly(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.IsReadOnly;
}

}
}



Thanks

Priya

Continue reading...
 
Back
Top