TFileStream A file-name-based constructor relies on the WIndows CreateFile API call to create a file descriptor that will be used to access the file. The API itself has several parameters, and Create Disposition is especially interesting for you: if you specify CREATE_NEW , the function will fail if the file already exists. You can take advantage of this by calling CreateFile yourself, and then using the return handle to create a TFileStream . You can do this because TFileStream inherits from THandleStream , inherits its descriptor-based constructor, and owns the descriptor (calls CloseHandle in the descriptor you pass to the constructor).
Since this depends on the OS-provided CreateFile function, it will be safe in three modes (without race conditions between FileExists() and the actual creation of the file. It also blocks the old application from accessing the newly created file until you actually close the handle .
var FH: NativeUInt;
source share