Currently I use this function, based on JCL code, which works fine:
function IsDirectoryWriteable(const AName: string): Boolean;
var
FileName: PWideChar;
H: THandle;
begin
FileName := PWideChar(IncludeTrailingPathDelimiter(AName) + 'chk.tmp');
H := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE, 0, nil,
CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0);
Result := H <> INVALID_HANDLE_VALUE;
DeleteFile(FileName);
end;
Is there anything I could improve with the flags?
Can the test be done without actually creating a file?
Or is this functionality even already available in one of the RTL or Jedi libraries?
Actually writing to the directory is the simpliest way to determine if the directory is writable. There are too many security options available to check individually, and even then you might miss something.
You also need to close the opened handle before calling
DeleteFile(). Which you do not need to call anyway since you are using theFILE_FLAG_DELETE_ON_CLOSEflag.BTW, there is a small bug in your code. You are creating a temporary
Stringand assigning it to aPWideChar, but theStringgoes out of scope, freeing the memory, before thePWideCharis actually used. YourFileNamevariable should be aStringinstead of aPWideChar. Do the type-cast when callingCreateFile(), not before.Try this: