Hi
I am creating handles to files that I need to only read (not create new versions of, not write to, and not create if they don't exist) using (courtesy of EngKin at
http://forum.lazarus.freepascal.org/index.php/topic,24765.msg149502.html#msg149502):
{$ifdef windows}
if IOResult <> 0 then
begin
ws := UTF8ToUTF16(FileName);
security.nLength := Sizeof(TSecurityAttributes);
security.bInheritHandle := true;
security.lpSecurityDescriptor := nil;
filerec(f).handle:=CreateFileW(@ws[1],GENERIC_READ, file_Share_Read, @security, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
end;
{$endif windows}
However, if the file is open by another application, my program reports the "Invalid file handle" error. I gather the key element is the dwCreationDisposition part...in my case, "OPEN_EXISTING". I read
http://msdn.microsoft.com/en-gb/library/windows/desktop/aa363858%28v=vs.85%29.aspx and gather my options are :
CREATE_ALWAYS : Creates a new file, always.
CREATE_NEW : Creates a new file, only if it does not already exist.
OPEN_ALWAYS : Opens a file, always. // sounded promising, except it states if the file doesn't exist, it creates it!
OPEN_EXISTING : Opens a file or device, only if it exists. // my current option, but seems to fail if another program has it open already
TRUNCATE_EXISTING : Opens a file and truncates it so that its size is zero bytes, only if it exists.
I have looked at the API docs here but I'm still rather unclear as to what value to pass to ensure that my program can read the file, even if it is open by something else?