Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a file to be copied completely?

I have a thread which polls a folder for new files. The problem is that it sees a new file and starts working on it even before the file has been completely copied by another process. Because of this the poller gets file used by another process error.

Is there a way to check the file is free to use or get notified? We can certainly use exception handling code, but is there a better way?

Tech: .NET 2.0/C#

Update:

  • Found out from other answers that if we have access to the app writing the file then better design is to start with some other extension .tmp and then rename it after copying.

  • The FileStream.Lock could be used if we don't control the source application

like image 505
thewpfguy Avatar asked Nov 06 '22 09:11

thewpfguy


1 Answers

We attempt to get a lock on the file before processing it and handle the IOException rather than a generic exception during the attempt to read the file.

See FileStream.Lock on MSDN.

like image 179
Jimmie R. Houts Avatar answered Nov 12 '22 16:11

Jimmie R. Houts