FileSystemWatcher with ASP .NET MVC 4

My MVC app had to process ZIP pack, which was provided to a special folder by external source. The file was containing some data which should be processed by my system. At the time the file appeared, the system should immediately start processing. NET Platform provides a cool class called FileSystemWatcher, which allows monitoring the contents of a folder. This proved to be the ideal solution to avoid using the cron mechanism. To implement the engine I had to do few things:

1. Create  FileSystemWatcher instance and stick it to watch directory
 var fsw = new FileSystemWatcher
                Filter = "*.zip",
                Path = ConfigurationManager.AppSettings["watchDirectoryPath"],
                EnableRaisingEvents = true,
                IncludeSubdirectories = false

2. Set FileSystemEventHandler and write some logic (unzip file with DotNetZip into some dir)

 fsw.Created += new FileSystemEventHandler(OnCreated);
static void OnCreated(object sender, FileSystemEventArgs e)
            string zipToUnpack = e.FullPath;
            string unpackDirectory = ConfigurationManager.AppSettings["unpackDirectory"];

            using (ZipFile zip = ZipFile.Read(zipToUnpack))
                foreach (ZipEntry ze in zip)
                    ze.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);

3. Register Watcher while Application starts (Application_Start in Global.asax.cs). I wrapped this code into MonitorConfig class with RegisterWatchers method.

 protected void Application_Start()


Source code is avaliable here.

Laptopy poleasingowe Białystok

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *