I have to create a Windows service which monitors a specified folder for new files and processes it and moves it to other location.
I started with using FileSyste
At program startup, use Directory.GetFiles(path) to get the list of files.
Then create a timer, and in its elapsed event call hasNewFiles:
static List hasNewFiles(string path, List lastKnownFiles)
{
List files = Directory.GetFiles(path).ToList();
List newFiles = new List();
foreach (string s in files)
{
if (!lastKnownFiles.Contains(s))
newFiles.Add(s);
}
return new List();
}
In the calling code, you'll have new files if:
List newFiles = hasNewFiles(path, lastKnownFiles);
if (newFiles.Count > 0)
{
processFiles(newFiles);
lastKnownFiles = newFiles;
}
edit: if you want a more linqy solution:
static IEnumerable hasNewFiles(string path, List lastKnownFiles)
{
return from f in Directory.GetFiles(path)
where !lastKnownFiles.Contains(f)
select f;
}
List newFiles = hasNewFiles(path, lastKnownFiles);
if (newFiles.Count() > 0)
{
processFiles(newFiles);
lastKnownFiles = newFiles;
}