-11 Vote

Lazarus: Copy file that is in use

Article by Stefan Trost | Last update on 2022-12-27 | Created on 2015-02-12

If a file is opened, for example, in OpenOffice, Word or any other program, the program marks the file as "in use".

If we would like to copy such a file with Lazarus' CopyFile function, we get the error message "Unable to open file". Nevertheless, it is possible to copy exactly this file with the key combination CTRL + C and CTRL + V on Windows, although it should actually be blocked and inaccessible.

How can it be possible that copying is working in Windows but not in Lazarus? And how can we change this behavior?

FileOpenUTF8 - fmShareDenyNone or fmShareDenyWrite

When following the CopyFile-function to its definition in the unit FileUtil, we can see where the fault lies. Here, we can find the following line for reading the file:

SrcHandle := FileOpenUTF8(SrcFilename, fmOpenRead or fmShareDenyWrite);

The fmShareDenyWrite claims exclusive write access to the file. This prevents other applications from writing to the file. Other programs are only allowed to open the file for reading.

However, this is our problem here. With claiming that exclusive right when trying to copy a file, the operating system returns an error message in the case that the file is currently opened in another application (because in this case, we cannot claim this right).

When using fmShareDenyNone instead, it is working:

SrcHandle := FileOpenUTF8(SrcFilename, fmOpenRead or fmShareDenyNone);

Using fmShareDenyNone, we are not preventing reading and writing by other applications and this make it work even if the files opened in another program.

Should I change the original function?

Nevertheless, you should be careful with such modifications and you should keep in mind that with using the original fmShareDenyWrite, it is not possible that other applications are changing the source file during the copy process. With fmShareDenyNone it is.

So, it would be advisable not to change the original function but creating an own function containing this modification that is only used if exactly this behavior is needed.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.