Create a locked file (Views: 102)


I was using temporary files on the root of the disk, but the user could try to modify it when my application was open and I didn't want that. Here's how to prevent it.


Solve 1:

There are two ways of doing that, but one, with the use of Windows' APIs (LockFileEx and UnlockFileEx) using the parameter LOCKFILE_EXCLUSIVE_LOCK was not good for my case, so I found that:

Create the file with the OpenFile function and handle it:

hMyLockedFile := OpenFile('c:\variables.dat', ofStruct, OF_CREATE or OF_READWRITE or

Now, you can work with your file, but users cannot change it!

A last comment:
I found that in Win32 SDK Reference, so if you need to know more (and there's more to know: believe me!) you should use it!

Solve 2:

  SA: TSecurityAttributes;
  MyText: array[0..500] of char;
  BWritten: DWord;
  OK: Boolean;
  MyText := 'Mark Halter' + chr(13) + Chr(10) + 'Südstr. 6';

  with SA do
    nLength := SizeOf(SA);
    bInheritHandle := True;
    lpSecurityDescriptor := nil;

  Hndl := CreateFile('d:\temp\testfile.txt', // filename
    GENERIC_READ or GENERIC_WRITE, // read/write access
    0, // do not share file
    @SA, // Security Attributes
    CREATE_ALWAYS, // create file everytime
    FILE_ATTRIBUTE_NORMAL, // set normal attributs

  OK := WriteFile(Hndl,


<< Back to main page