Aly
Aly

Reputation: 16255

Moving files from watched folder in C#

I am using a FileSystemWatcher which uses the Created event to listen for when I copy files into this directory. this method is below:

private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
   System.IO.Directory.Move(fileSystemWatcher1.Path+@"\"+e.Name, fileSystemWatcher1.Path + @"\Processing\"+e.Name);
}

The problem is if I copy a big file into this directory, such that it takes about 30 seconds to copy, this method is called as soon as the first byte is written to the folder and tries to move a file which is being used by another process so fails.

Any thoughts?

thanks

Upvotes: 0

Views: 1609

Answers (4)

Aly
Aly

Reputation: 16255

I have done this:

while(true){
  try
  {
     using (Stream stream = new FileStream("MyFilename.txt"))
     {
        break;
     }
  } catch {
     Thread.Sleep(1000);
  }
}

it seems to do the job

Upvotes: 1

Dave Markle
Dave Markle

Reputation: 97671

In cases like this, I like to have the copying process move the file over using a temporary filename which will not be recognized by the watcher.

Then I rename the file to its real name. The rename takes very little time and will not cause the file to be "in use".

Upvotes: 3

driis
driis

Reputation: 164281

Perhaps you could do this by also listening to the "Changed" event, and only try to copy the file after a cool-off period. That is, after receiving "Created", wait 5 seconds before copying the file, and reset the time to zero each time you receive the Changed event.

Upvotes: 1

ChrisF
ChrisF

Reputation: 137128

You might need to combine a couple of solutions to get this working.

  1. When the event fires start a timer to wait a while (30 seconds?) so that the file creation has time to complete. Then move the file away.

  2. Trap the error and retry later.

Or when the file arrives add it's name to a queue and then have a separate process that moves files off the queue. In this case if you get a "file in use" error you could simply readd the file to the back of the queue thus giving it more time to complete.

Upvotes: 3

Related Questions