{"id":170,"date":"2012-04-08T22:12:18","date_gmt":"2012-04-08T14:12:18","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=170"},"modified":"2018-09-03T21:49:13","modified_gmt":"2018-09-03T13:49:13","slug":"how-to-monitor-a-folder-for-new-files-from-your-c-application","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-monitor-a-folder-for-new-files-from-your-c-application\/","title":{"rendered":"How to monitor a folder for new files from your C# application"},"content":{"rendered":"<p>Suppose that you need to write a C# application to run in an environment where there are many batch applications running and <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-create-a-file-in-c\/\" title=\"How to create a file in C#\" target=\"_blank\">creating files<\/a> as their output. <\/p>\n<p>Your application is one of them and is required to process files produced by others. How are you going to know from your C# application when these files are ready?<\/p>\n<p>In this post, I document the use of a .Net facility that can help you achieve that.<\/p>\n<h3>The FileInputMonitor class<\/h3>\n<p>Let us create a sample use case. Suppose there is a <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/c-facilities-for-dealing-with-folders\/\" title=\"C# facilities for dealing with folders\" target=\"_blank\">folder<\/a> which other applications will deposit their file output on a daily basic. The naming convention of the file will be <strong>report-for-<<em>CURRENT_DATE-YYYY-MM-DD<\/em>><\/strong>. For instance, on 7th April 2012, the file will be named as <strong>report-for-2012-04-07<\/strong>.<\/p>\n<p>The following <code>FileInputMonitor<\/code> class is an implementation for the sample use case.  <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing System;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Threading;\r\n\r\npublic class FileInputMonitor\r\n{\r\n\r\n    private FileSystemWatcher fileSystemWatcher;\r\n    private string folderToWatchFor \r\n        = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + &quot;toTechcoil&quot;;\r\n\r\n    public FileInputMonitor()\r\n    {\r\n\r\n        fileSystemWatcher = new FileSystemWatcher(folderToWatchFor);\r\n        fileSystemWatcher.EnableRaisingEvents = true;\r\n\r\n        \/\/ Instruct the file system watcher to call the FileCreated method\r\n        \/\/ when there are files created at the folder.\r\n        fileSystemWatcher.Created += new FileSystemEventHandler(FileCreated);\r\n\r\n    } \/\/ end FileInputMonitor()\r\n\r\n    private void FileCreated(Object sender, FileSystemEventArgs e)\r\n    {\r\n\r\n        if (e.Name == &quot;report-for-&quot; + System.DateTime.Now.ToString(&quot;yyyy-MM-dd&quot;)) \r\n        {\r\n            ProcessFile(e.FullPath);\r\n        } \/\/ end if\r\n\r\n    } \/\/ end public void FileCreated(Object sender, FileSystemEventArgs e)\r\n\r\n    private void ProcessFile(String fileName)\r\n    {\r\n        FileStream inputFileStream;\r\n        while (true) \r\n        {\r\n            try\r\n            {\r\n                inputFileStream = new FileStream(fileName, \r\n                    FileMode.Open, FileAccess.ReadWrite);\r\n                StreamReader reader = new StreamReader(inputFileStream);\r\n                Console.WriteLine(reader.ReadToEnd());\r\n                \/\/ Break out from the endless loop\r\n                break;\r\n            }\r\n            catch (IOException)\r\n            {\r\n                \/\/ Sleep for 3 seconds before trying\r\n                Thread.Sleep(3000);\r\n            } \/\/ end try\r\n        } \/\/ end while(true)\r\n    } \/\/ end private void ProcessFile(String fileName)\r\n   \r\n} \/\/ end public class FileInputMonitor\r\n<\/pre>\n<h4>Monitoring whether new files are created in a folder with System.IO.FileSystemWatcher<\/h4>\n<p>When an instance of <code>FileInputMonitor<\/code> is created, we also create an instance of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemwatcher.aspx\" title=\"MSDN reference for System.IO.FileSystemWatcher\" target=\"_blank\"><code>System.IO.FileSystemWatcher<\/code><\/a> class, passing it the directory path of the folder to monitor. <\/p>\n<p>After creating an instance of the FileSystemWatcher, we proceed to configure it. In order to enable the <code>FileSystemWatcher<\/code> instance to notify our application when files are created in the folder, we <strong>must<\/strong> first set its <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemwatcher.enableraisingevents.aspx\" title=\"MSDN reference for System.IO.FileSystemWatcher.EnableRaisingEvents Property\" target=\"_blank\"><code>EnableRaisingEvents<\/code><\/a> property to true.<\/p>\n<p>We then add a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemeventhandler.aspx\" title=\"MSDN reference for the System.IO.FileSystemEventHandler Delegate\" target=\"_blank\"><code>System.IO.FileSystemEventHandler<\/code><\/a> delegate to the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemwatcher.created.aspx\" title=\"MSDN reference for System.IO.FileSystemWatcher.Created event\" target=\"_blank\"><code>Created<\/code><\/a> event so that control can be delegated to the <code>FileCreated<\/code> method of our <code>FileInputMonitor<\/code> class whenever a new file is created. <\/p>\n<h4>Checking whether an expected file is ready for processing<\/h4>\n<p>When the <code>FileCreated<\/code> method is executed, we check whether the new file is what our application wants via the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemeventargs.name.aspx\" title=\"MSDN reference for FileSystemEventArgs::Name property\" target=\"_blank\">Name<\/a> property of the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filesystemeventargs.aspx\" title=\"MSDN reference for System.IO.FileSystemEventArgs\" target=\"_blank\"><code>System.IO.FileSystemEventArgs<\/code><\/a> instance. If the file is designated for our application, the <code>ProcessFile<\/code> method is called to process the file.<\/p>\n<p>In the <code>ProcessFile<\/code> method, we attempt to get an instance of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filestream.aspx\" title=\"MSDN reference to System.IO.FileStream\" target=\"_blank\"><code>System.IO.FileStream<\/code><\/a> with <code>ReadWrite<\/code> access to <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-read-from-file-in-c\/\" title=\"How to read from file in C#\" target=\"_blank\">read from the file<\/a> in an infinite loop. This is because the batch application may still be <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-write-to-file-in-c\/\" title=\"How to write to file in C#\" target=\"_blank\">writing to the file<\/a> when our application received notification of the new file. <\/p>\n<p>In the event when the instance of <code>FileStream<\/code> cannot be retrieved, the application will wait for 3 seconds via a call to <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/d00bd51t.aspx\" title=\"MSDN reference for System.Threading.Thread.Sleep Method\">Thread.Sleep<\/a>. Upon success acquisition of the FileStream instance, the code reads from the file, output it to console and break out of the infinite loop.<\/p>\n<h3>Using the FileInputMonitor class<\/h3>\n<p>To conclude this post, the following is a program that maintains an instance of the <code>FileInputMonitor<\/code> to monitor the <strong>toTechcoil<\/strong> folder that is in the same directory as the executable. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class Program\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        FileInputMonitor fileInputMonitor = new FileInputMonitor();\r\n        Console.Read();\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n\r\n} \/\/ end public class Program\r\n<\/pre>\n<h3>Other posts that may interests you<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-save-and-load-objects-to-and-from-file-in-c\/\" title=\"How to save and load objects to and from file in C#\" target=\"_blank\">How to save and load objects to and from file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/my-experience-with-system-data-sqlite-in-c\/\" title=\"My experience with System.Data.SQLite in C#\" target=\"_blank\">My experience with System.Data.SQLite in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/downloading-a-file-from-via-http-post-and-http-get-in-c\/\" title=\"Downloading a file via HTTP post and HTTP get in C#\" target=\"_blank\">Downloading a file via HTTP post and HTTP get in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" title=\"A mechanism for serving HTTP requests in C#\" target=\"_blank\">A mechanism for serving HTTP requests in C#<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-2K\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2K&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2K&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F170&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>Suppose that you need to write a C# application to run in an environment where there are many batch applications running and <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-create-a-file-in-c\/\" title=\"How to create a file in C#\" target=\"_blank\">creating files<\/a> as their output. <\/p>\n<p>Your application is one of them and is required to process files produced by others. How are you going to know from your C# application when these files are ready?<\/p>\n<p>In this post, I document the use of a .Net facility that can help you achieve that.<\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,113,107,106],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-2K","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/170"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=170"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/170\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=170"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=170"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=170"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}