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