tags:

views:

103

answers:

3

How we can check if a directory is readOnly or Not?

+3  A: 

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

try this code

function DirIsReadOnly(Path:string):Boolean;
var
 attrs    : Integer;
begin
 attrs  := FileGetAttr(Path);
 Result := (attrs  and faReadOnly) > 0;
end;
RRUZ
Idea: the code could (as a 'special bonus') throw an exception if Path points to "something else than a directory" - or use Assert(DirectoryExists(Path))?
mjustin
+1  A: 

In Windows API way, it 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');
Vantomex
+1  A: 

Testing if the directory's attribute is R/O is only part of the answer. You can easily have a R/W directory that you still can't write to - because of Access Rights.

The best way to check if you can write to a directory or not is - to try it:

FUNCTION WritableDir(CONST Dir : STRING) : BOOLEAN;
  VAR
    FIL : FILE;
    N   : STRING;
    I   : Cardinal;

  BEGIN
    REPEAT
      N:=IncludeTrailingPathDelimiter(D);
      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)
    EXCEPT
      Result:=FALSE
    END;
    IF Result THEN BEGIN
      CloseFile(FIL); 
      ERASE(FIL)
    END
  END;
HeartWare
looks like COBOL or FORTRAN to me at first look :)
mjustin
and as brute as code from COBOL age, heh
What you did is close to the worst way. Unnecessary filesystem, hd burden. Next, what if you have some sort of fs change subscribers attached? The best way is just to write whatever you planned on writing there. If the directory is protected, you'll get an error. That's it.
himself
Agreed. But if for some reason you NEED to know BEFOREHAND if the directory is writable, the only way is - as you yourself are implying - to just do it. The above function just does this and returns the result.
HeartWare