title: Windows Service to Watch the Downloads Directory for Files in C#
body: <p>I am fairly new to the Windows world, as most of my primary development is with UNIX systems. A specific request from a customer came in and asked if I could write a windows service to watch the Downloads folder for any downloaded content, and move it to their Documents folder. For some reason they didn't want to just change their default download directory on their browser. </p>
  
  <p>So to give the customer what they asked I thought I would give it a shot. Here is my attempt: </p>
  
  <pre><code>    protected override void OnStart(string[] args)
      {
          watch();
      }
  
      public void OnDebug()
      {
          OnStart(null);
      }
  
      protected override void OnStop()
      {
      }
  
      String path = null;
      private void watch()
      {
          FileSystemWatcher watcher = new FileSystemWatcher();
          string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
          path = Path.Combine(pathUser, "Downloads");
          watcher.Path = path;
          watcher.NotifyFilter = NotifyFilters.LastWrite;
          watcher.Filter = "*.*";
          watcher.Changed += new FileSystemEventHandler(OnChanged);
          watcher.EnableRaisingEvents = true;
      }
  
      private void OnChanged(object source, FileSystemEventArgs e)
      {
          String pUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
          String directoryName = Path.Combine(pUser, "Documents"); ;
          DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
          if (dirInfo.Exists == false)
              Directory.CreateDirectory(directoryName);
  
          List&lt;String&gt; MyFiles = Directory
                             .GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();
  
          foreach (string file in MyFiles)
          {
              FileInfo mFile = new FileInfo(file);
              // to remove name collusion
              if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
                  mFile.MoveTo(dirInfo + "\\" + mFile.Name);
          }
      }
  </code></pre>
  
  <p>I tested my code in debug mode and when the service is running and I go to download a file, the download fails. Visual Studio then pops up with this error: </p>
  
  <p><code>"An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
  Additional information: The process cannot access the file because it is being used by another process."</code></p>
  
  <p>The error is thrown on:</p>
  
  <p><code>mFile.MoveTo(dirInfo + "\\" + mFile.Name);</code></p>
  
  <p>How can I fix this?</p>