PDA

View Full Version : Windows file copy in progress, how can I tell?



tgreaves
23rd February 2009, 16:29
I want write a program that will syncronize files between two directories.. Suppose (in windows) im copying file(s) into the "from" directory and my program runs to sync the files, I dont want it to try to sync a file that im copying into the "from" directory.. Is there a way to tell if the file is "being copied"?

Is a file thats "being copied" read-only? If so, can I just try to open the file read-write in my program and if it fails just skip that file?

Let me know if this doesnt make sense or if more info is needed..

^NyAw^
23rd February 2009, 17:05
Hi,

I had the same problem ago and this is how I solved:

Before copying the file itself, create a "sameName.lock" file, then copy the file and finally remove the "sameName.lock" file.
On the other application you have to check if the file "sameName.lock" exists before trying to use it. If it exists, it is being copied and can't access it, if not exists you can access it.

Maybe there is a better way to do this, but I'm sure that it works.

tgreaves
23rd February 2009, 17:38
Well the problem is, I want to know if windows is copying the file into the directory that im checking.. Does windows create a .lock file or anything like that?

rexi
23rd February 2009, 17:39
I don't know for sure if it is the same for Windows (though it would be insane if it behaved different), but on Unix you can't open a file twice to write to it. So you could try opening the file for writing, and if that failed, you would know that some other process is writing to that file, i.e. copying it to the directory at the moment.

Compared to lock files, the advantage of this approach is that you can detect a copy in progress even if you have no control of how a file is copied to that directory, i.e. "anyone can copy there", in opposition to "only programs you have control of (and that can, in turn, create lock files)" can copy there.

tgreaves
23rd February 2009, 17:42
Understood.. I just tried to copy something into a directory and tried to run it while it was copying and it gave me a "another program is currently using this file" message.. So ill try to open the file for writing and see if that gives me an error on the open..

Ill let you all know how it turns out..