FileSystemWatcher with ASP .NET MVC 4

One day I had very nice task to do. My Mvc app had to process ZIP pack, which was provided to special folder by cilent. The file was containing some important files, but this does not really matter. When the file appears, it should automatically start a process X. NET Platform provides cool class called FileSystemWatcher, which allows to monitor the contents of a folder. To complete my case 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()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            MonitorConfig.RegisterWatchers();
        }

Above code works very well, 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 *