Pause code until file fully downloaded

R

Rob Oldfield

I have a situation where I need to scan a folder for downloaded files and
then process those files. I have a file system watcher which is looking for
the creation of a file but clearly I want wait until the file is completely
downloaded before I start trying to use it. At present I'm trying this...

Dim fi As New FileInfo(fle)
'Don't try to read while still being written
Do While fi.Length <> sz
s = TimeOfDay.Second
Do While TimeOfDay.Second = s
Loop
sz = fi.Length
Loop

....but that's going wrong on the sz=fi.length line (not immediately, but
intermittently)... telling me that the file doesn't exist.

Does anyone have a better way of approaching this?

(...and no, the sensible answer of getting the data provider to add the
creation of a 0k control file at the end of the download isn't an option.)
 
R

Robbe Morris [C# MVP]

you could try this:

Do While fi.length <> sz
System.Threading.Thread.Sleep(1000)
Loop
 
R

Rob Oldfield

More efficient (and thanks for that), but still doesn't get around the
problem of it thinking that fi doesn't exist.
 
C

Chris Dunaway

What the FileSystemWatcher really needs is a FileClosed event! But
alas, we don't have that.

One technique similar to the one Rob specified is to attempt to open
the file exclusively. If that fails, it means the file is still in
use.

Do you control the downloading of the file? You could send the files
with a temporary name and then rename the file to its final name and
then have the FileSystemWatcher watch for the rename event.

Good Luck
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top