title: How to deal with rapid consecutive file creation in a folder watched by a FileSystemWatcher?
body: <p>I have a folder being watched by a service with a <code>FileSystemWatcher</code> and I used this <a href="https://stackoverflow.com/a/3822355/4466640">Answer</a> to help me for large files being written to it.</p>
  
  <p>However, I came to an issue if there are consecutive file creations about(100MB or more).</p>
  
  <p><strong>Q:</strong> How would can I tackle this issue? Like example around 10 files (100MB each) written to my folder.</p>
  
  <p><strong>Note:</strong> This folder is accessed through my network. There could be files created but not really complete/finished. the <code>FileSystemWatcher</code> could process the file without it being written completely.</p>
  
  <p>Current code for checking if opening file throws an exception</p>
  
  <pre><code>private static bool IsFileLocked(FileInfo file)
      {
          FileStream stream = null;
          try
          {
              stream = file.Open(FileMode.Open,
                       FileAccess.Read, FileShare.None);
          }
          catch (IOException)
          {
              //the file is unavailable because it is:
              //still being written to
              //or being processed by another thread
              //or does not exist (has already been processed)
              return true;
          }
          finally
          {
              if (stream != null)
                  stream.Close();
          }
  
          //file is not locked
          return false;
      }
  </code></pre>
  
  <p>Current code checking if there is a file created.</p>
  
  <pre><code>    private void FSWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
      {
          var files = getFiles(FSWatcher.Path); //stores all filenames in the directory in a list
          if (files.Count() &gt; 0)
          {
              foreach (string file in files)
              {
                  FileInfo file_info = new FileInfo(file);
                  while (IsFileLocked(file_info))
                  {
                      Thread.Sleep(5000); //Sleep if file unavailable
                  }
                  //code to process the file
              }
              //some code here
          }
      }
  </code></pre>