Seham Hammad

Seham Hammad

  • NA
  • 73
  • 600

Schedule timer to run tasks on different times to monitor files in c#

Oct 17 2020 3:43 AM

Hello experts

I want to monitor files in different folders using timer to schedule tasks at different times within worker service in c#. I have got the idea working if I hard code two interfaces but if I want to do it for multiple tasks how will i run my monitorFiles function to do that using the Task.delay.

the code is following:

Thanks in advance.

how to run the MonitorAndProcessFiles to be called instead of the run_elapsed method in the timer call back function.
 
private void MonitorAndProcessFiles(object sender, ElapsedEventArgs e)
{
/*Check if dest directory exist, if yes then move the files */
try
{
for (int i = 0; i < configsItems.Count; i++)
{
if (configsItems.Count > 0)
{
rootPath = configsItems[i].Source;
destPath = configsItems[i].Destination;
regex = configsItems[i].regx;
bool directoryExists = Directory.Exists(destPath);
if (directoryExists)
{
eventLog1.WriteEntry($"The [{rootPath}] exists.");
log.Information($"The [{rootPath}] exists.");
var files = Directory.GetFiles(rootPath).OrderBy(f => new FileInfo(f).CreationTime).Where(item => regex.IsMatch(item));
eventLog1.WriteEntry($"Moving files from Folder: {rootPath}");
log.Information($"Moving files from Folder: {rootPath}");
foreach (string file in files)
{
try
{
File.SetAttributes(destPath, FileAttributes.Normal);
File.Move(file, $"{destPath}{Path.GetFileName(file)} ");
eventLog1.WriteEntry($"File {Path.GetFileName(file)} moved to the the {destPath} successfullly");
log.Information($"File {Path.GetFileName(file)} moved to the the {destPath} successfullly");
}
catch (IOException)
{
eventLog1.WriteEntry($"Failed moving {Path.GetFileName(file)} to the {destPath}, File is being used by another process!", EventLogEntryType.Error);
log.Information($"Failed moving {Path.GetFileName(file)} to the {destPath}, File is being used by another process! ");
}
}
}
else
{
Directory.CreateDirectory(destPath);
}
}
}
}//end of main try block
catch (Exception)
{
eventLog1.WriteEntry("Can not access folders over the network", EventLogEntryType.Error);
log.Information("Can not access folders over the network");
}
}/*End of MonitorAndProcessFiles*/

Attachment: WorkerServiceApp.zip

Answers (2)