Is there any way through which I can lock the XML file while I am writing into it using Delphi?

190 views Asked by At

I have a multiple processes which write into same XML file. I am using NativeXML library.

I want to lock my file while any process writes into it so that the data in file should not be overwitten.

1

There are 1 answers

0
Remy Lebeau On

When you create a file, create it with exclusive rights, or at least with write access sharing disabled, then write to it as needed. Nobody else will be able to open the file for writing until you close it first.

In fact, NativeXML already does exactly that when saving XML to a file via its SaveToFile() method. It uses a TFileStream, and that is the default behavior of TFileSteam when creating a new file.

But, if you need more control over the access rights, then you can create your own TFileStream object so you can fill in its constructor parameters as needed. Or create a THandleStream object that refers to a file handle that you create using Window's CreateFile() API directly. Then you can have NativeXml write to that stream via its SaveToStream() method.