Sometime we need a program to watch over particular Directory and then based on the Input,we need to perform some other task in parallel.
Here, I am providing a part of program(a window service)that uses FileSystemWacther to monitor a Directory and then based on Input perform some other task parallely.
Note: You should learn FileSystemWatcher before going through this Post.

OnStartis the Window Service method .You can use Console pgm or TaskScheduler also.
  1. protected override void OnStart(string[] args)
  2. {
  3. current_directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  4. try
  5. {
  6. strDir = ConfigurationManager.AppSettings["Directory"];
  7. fileMask = ConfigurationManager.AppSettings["FileMask"];
  8. strBatfile = ConfigurationManager.AppSettings["Batch"];
  9. strlog = ConfigurationManager.AppSettings["Log"];
  10. Task.Factory.StartNew(QueueHandler);
  11. var fsw = new FileSystemWatcher();
  12. fsw.Created += (o, e) =>
  13. {
  14. // add a file to the queue
  15. filenames.Enqueue(e.FullPath);
  16. };
  17. fsw.Path = strDir + "\\";
  18. fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
  19. | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  20. fsw.Filter = fileMask;
  21. fsw.EnableRaisingEvents = true;
  22. fsw.Deleted += new FileSystemEventHandler(OnDeleated);
  23. fsw.Renamed += new RenamedEventHandler(OnRenamed);
  24. fsw.EnableRaisingEvents = true;
  25. }
  26. catch (Exception exception)
  27. {
  28. CustomException.Write(CustomException.CreateExceptionString(exception.ToString()));
  29. }
  30. }
And now we need to provide the function that runs in parallel (QueueHandler) using Queues.
  1. static void QueueHandler()
  2. {
  3. bool run = true;
  4. AppDomain.CurrentDomain.DomainUnload += (s, e) =>
  5. {
  6. run = false;
  7. filenames.Enqueue("stop");
  8. };
  9. try
  10. {
  11. while (run)
  12. {
  13. string filename;
  14. if (filenames.TryDequeue(out filename) && run)
  15. {
  16. var proc = new Process();
  17. proc.StartInfo.FileName = Service1.strBatfile; //here .exe can be added
  18. proc.Start();
  19. ;
  20. Log.getLogger("File Processed after executing batch\.exe: Filename - :" + filename + " " + "Batch File Executed- > " + Service1.strBatfile + " at timestamp : " + DateTime.Now.ToString(), Service1.strlog);
  21. proc.WaitForExit(); // this blocks until the process ends....
  22. }
  23. }
  24. }
  25. catch (Exception exception)
  26. {
  27. CustomException.Write(CustomException.CreateExceptionString(exception.ToString()));
  28. }
Note: You can write your custom exception .How you want to Log depends on you.