How can I use Delphi to test if a Directory is writeable?
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 the FILE_FLAG_DELETE_ON_CLOSE
flag.
BTW, there is a small bug in your code. You are creating a temporary String
and assigning it to a PWideChar
, but the String
goes out of scope, freeing the memory, before the PWideChar
is actually used. Your FileName
variable should be a String
instead of a PWideChar
. Do the type-cast when calling CreateFile()
, not before.
Try this:
function IsDirectoryWriteable(const AName: string): Boolean;
var
FileName: String;
H: THandle;
begin
FileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp';
H := CreateFile(PChar(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;
if Result then CloseHandle(H);
end;
Here is my version using GetTempFileName
which will attempt to create a unique temp file in the target directory:
function IsDirecoryWriteable(const AName: string): Boolean;
var
TempFileName: array[0..MAX_PATH] of Char;
begin
{ attempt to create a temp file in the directory }
Result := GetTempFileName(PChar(AName), '$', 0, TempFileName) <> 0;
if Result then
{ clean up }
Result := DeleteFile(TempFileName);
end;