Recent

Author Topic: How to determine if the user has permission to write in a specified directory  (Read 18519 times)

laztest

  • New Member
  • *
  • Posts: 10
I want my software to determine if the user has write permission for a folder they specify. I initially thought I could use getfileattr, however on Linux this returns the wrong answer if the folder is writeable but only for a different user (e.g. the user is not the owner of the folder, and does not have write permissions). The code below returns the correct answer, but it seems very clumsy. Can anyone think of an elegant way to do this?

const
{$IFDEF UNIX}
PathDelim = '/';
{$ELSE}
PathDelim = '\';
{$ENDIF}

function DirectoryWriteable (lDir: string): boolean;
//uses SysUtils
//when passed folder e.g. /usr/lib/ will return true if
//user has permission to create files in that folder...
Var
  i : Longint;
  lFilename: string;
Begin
  result := false;
  if length(lDir) < 1 then
     exit;
  if lDir[length(lDir)] <>  PathDelim then
      lFilename := lDir + pathdelim + 'dummy.dum'
  else
      lFilename := lDir + 'dummy.dum';
  if fileexists (lFilename) then
     exit; //do not overwrite existing file
  i:=FileCreate (lFilename);
  if i=-1 then
    Halt(1);
  FileClose(i);
  DeleteFile(lFilename);
  result := true;
end;

procedure TForm1.Button1Click(Sender: TObject);
//uses FileCtrl
var
  Dir : string;
begin
  Dir :=  GetCurrentDir;  // Set the starting directory
  // Ask the user to select using a completely different dialog!
  if NOT SelectDirectory(Dir, [sdAllowCreate], 0) then
     exit;

  if DirectoryWriteable(Dir) then
     showmessage('Writeable '+Dir)
  else
      showmessage('Not writeable '+Dir);

end;

theo

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1930

laztest

  • New Member
  • *
  • Posts: 10
Theo-
  Thanks for the fast response. This was the solution I was looking for.

 

TinyPortal © 2005-2018