Create a locked file (Views: 27)
Problem/Question/Abstract: 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: hMyLockedFile := OpenFile('c:\variables.dat', ofStruct, OF_CREATE or OF_READWRITE or 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: var SA: TSecurityAttributes; MyText: array[0..500] of char; BWritten: DWord; OK: Boolean; begin MyText := 'Mark Halter' + chr(13) + Chr(10) + 'Südstr. 6'; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; 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 0); OK := WriteFile(Hndl, MyText, StrLen(MyText), BWritten, nil); CloseHandle(Hndl); end; |