检查目录是否可读

时间:2010-10-15 08:12:16

标签: delphi

我们如何检查目录是否为readOnly?

5 个答案:

答案 0 :(得分:4)

您可以使用FileGetAttr函数并检查是否设置了faReadOnly标记。

试试这段代码

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

答案 1 :(得分:2)

测试目录的属性是否为R / O只是答案的一部分。由于访问权限,您可以轻松拥有一个仍然无法写入的R / W目录。

检查是否可以写入目录的最佳方法是 - 尝试:

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 :(得分:1)

版本HeartWare给出的很好,但包含两个错误。这个修改过的版本工作更加可靠,并有评论来解释发生了什么:

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;

答案 3 :(得分:0)

在Windows API方式中,它是:

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

答案 4 :(得分:0)

一种可能的方法是尝试列出该目录中的文件并检查状态。这样我们可以检查它是否可读。此答案适用于2009年或更低版本。请记住,我们必须检查该文件夹是否存在,然后检查该文件夹是否可读。您可以在http://simplebasics.net/delphi-how-to-check-if-you-have-read-permission-on-a-directory/

中找到实现
相关问题