Check if the directory is readable

How can we check if the directory is read only or not?

+7
delphi
source share
4 answers

you can use the FileGetAttr function and check if the faReadOnly flag is faReadOnly .

try this code

 function DirIsReadOnly(Path:string):Boolean; var attrs : Integer; begin attrs := FileGetAttr(Path); Result := (attrs and faReadOnly) > 0; end; 
+4
source share

Testing if the directory attribute is R / O is only part of the answer. You can easily have an R / W directory that you still cannot write, due to permissions.

The best way to check if you can write to the directory or not is to try:

 FUNCTION WritableDir(CONST Dir : STRING) : BOOLEAN; VAR FIL : FILE; N : STRING; I : Cardinal; BEGIN REPEAT N:=IncludeTrailingPathDelimiter(Dir); FOR I:=1 TO 250-LENGTH(N) DO N:=N+CHAR(RANDOM(26)+65) UNTIL NOT FileExists(N); Result:=TRUE; TRY AssignFile(FIL,N); REWRITE(FIL,1); Result:=FileExists(N); // Not sure if this is needed, but AlainD says so :-) EXCEPT Result:=FALSE END; IF Result THEN BEGIN CloseFile(FIL); ERASE(FIL) END END; 
+2
source share

The HeartWare version is not bad, but it contains two errors. These modified versions work more reliably and have comments to explain what happens:

 function IsPathWriteable(const cszPath: String) : Boolean; var fileTest: file; szFile: String; nChar: Cardinal; begin // Generate a random filename that does NOT exist in the directory Result := True; repeat szFile := IncludeTrailingPathDelimiter(cszPath); for nChar:=1 to (250 - Length(szFile)) do szFile := (szFile + char(Random(26) + 65)); until (not FileExists(szFile)); // Attempt to write the file to the directory. This will fail on something like a CD drive or // if the user does not have permission, but otherwise should work. try AssignFile(fileTest, szFile); Rewrite(fileTest, 1); // Note: Actually check for the existence of the file. Windows may appear to have created // the file, but this fails (without an exception) if advanced security attibutes for the // folder have denied "Create Files / Write Data" access to the logged in user. if (not FileExists(szFile)) then Result := False; except Result := False; end; // If the file was written to the path, delete it if (Result) then begin CloseFile(fileTest); Erase(fileTest); end; end; 
+1
source share

In the Windows API, this is:

 fa := GetFileAttributes(PChar(FileName)) if (fa and FILE_ATTRIBUTE_DIRECTORY <> 0) and (fa and FILE_ATTRIBUTE_READONLY <> 0) then ShowMessage('Directory is read-only'); 
0
source share

All Articles