Author: Christian Cristofori
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.
Answer:
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:
1
2 hMyLockedFile := OpenFile('c:\variables.dat', ofStruct, OF_CREATE or OF_READWRITE or
3 OF_SHARE_EXCLUSIVE);
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:
4 var
5 SA: TSecurityAttributes;
6 MyText: array[0..500] of char;
7 BWritten: DWord;
8 OK: Boolean;
9 begin
10 MyText := 'Mark Halter' + chr(13) + Chr(10) + 'Südstr. 6';
11
12 with SA do
13 begin
14 nLength := SizeOf(SA);
15 bInheritHandle := True;
16 lpSecurityDescriptor := nil;
17 end;
18
19 Hndl := CreateFile('d:\temp\testfile.txt', // filename
20 GENERIC_READ or GENERIC_WRITE, // read/write access
21 0, // do not share file
22 @SA, // Security Attributes
23 CREATE_ALWAYS, // create file everytime
24 FILE_ATTRIBUTE_NORMAL, // set normal attributs
25 0);
26
27 OK := WriteFile(Hndl,
28 MyText,
29 StrLen(MyText),
30 BWritten,
31 nil);
32
33 CloseHandle(Hndl);
34 end;
|