[DUG] CopyFile when File in use

John Bird johnkbird at paradise.net.nz
Wed Aug 15 18:02:41 NZST 2007


Sometimes I wish to copy a file that may be open for reading or updating a
record (not a database file).  The application doing the reading/updating is
using proper block locking and retrying if busy, so it should not be tripped
up by anything outside.

I am doing the copy so far using CopyFile which is a Win32 function.
However I suspect that there may be a bit of brutal crudeness in this
function similar to using a text file (as in assignfile(f,filename)) which
from my experience seems to open a file in exclusive read-only mode.  

In my experience there is a finer control using TFileStream, where I can do
such as:

fs:=Tfilestream.create(FileName,fmOpenRead or fmShareDenyNone);

To prevent interfering with any other applications.  I suspect the other
application can be tripped by the CopyFile, causing it to crash if they
collide at the same time as the file becomes suddenly locked for exclusive
read.

I am wondering if it might be a wiser idea to use a copyfile function based
on TFileStream instead, something like:

  fs1 := TFileStream.Create(aFile1, fmOpenRead or fmShareDenyNone);
  try
    fs2 := TFileStream.Create(aFile2, fmCreate);
    try
      {Forget about block reads and writes, just copy
       the whole darn thing.}
      bytescopied:=fs2.CopyFrom(fs1, 0);
    finally
      fs2.Free;
    end;
  finally
    fs1.Free;
  end;

I wonder if anyone could shed any light on this?

P.S. Before anyone says why am I trying to copy files that may be in use, I
cannot tell when some of the minor files are in use but still want to copy
them, but it is crucial it doesn't interfere with any data updates - that is
I prefer to get an invalid snapshot of one file than get nothing or block
either program.

P.P.S. I did find another subtle difference between reading a file using
either textfile (or untyped file) and TFileStream - that TFileStream will
read into its buffer binary zeros if they are present in the source file,
whereas the textfile/file routines seem to strip them out or replace them
with spaces.

John




More information about the Delphi mailing list