2004. november 27., szombat

How to check file and directory attributes


Problem/Question/Abstract:

How to check file and directory attributes

Answer:

The sample below works with the folder c:\temp .

procedure TForm1.Button1Click(Sender: TObject);
var
  Ergebnis: integer;
  Hidden: boolean;
  ReadOnly: boolean;
  Directory: boolean;
begin
  {Get the current file attributes and store them in a local bool variable.
  lbl_hidden, lbl_ReadOnly and lbl_Directory are TLabels}
  Ergebnis := fileGetAttr('C:\Temp');
  if Ergebnis and faHidden <> 0 then
  begin
    hidden := True;
    lbl_hidden.Caption := 'Hidden File';
  end
  else
  begin
    Hidden := False;
    lbl_hidden.Caption := 'Not a hidden file';
  end;
  if Ergebnis and faDirectory <> 0 then
  begin
    Directory := True;
    lbl_Directory.Caption := 'We have a directory';
  end
  else
  begin
    Directory := False;
    lbl_Directory.Caption := 'There is no directory';
  end;
  if Ergebnis and faReadOnly <> 0 then
  begin
    ReadOnly := True;
    lbl_ReadOnly.Caption := 'File is write-protected';
  end
  else
  begin
    ReadOnly := False;
    lbl_ReadOnly.Caption := 'File is not write-protected';
  end;
  refresh;
  sleep(4000);
  {Set attributes}
  FileSetAttr('C:\Temp', faHidden or faReadOnly or faDirectory);
  {Check set attributes and reset Ergebnis variable to original status}
  Ergebnis := FileGetAttr('C:\Temp');
  if Ergebnis and faHidden <> 0 then
  begin
    lbl_hidden.Caption := 'Attribute Hidden is set'; {TLabel}
    if not hidden then
      Ergebnis := Ergebnis xor fahidden;
  end
  else
    lbl_hidden.Caption := 'Attribute Hidden is not set';
  if Ergebnis and faReadOnly <> 0 then
  begin
    lbl_ReadOnly.Caption := 'Attribute Read Only is set';
    if not ReadOnly then
      Ergebnis := Ergebnis xor faReadOnly;
  end
  else
    lbl_ReadOnly.Caption := 'Attribute ReadOnly not set';
  if Ergebnis and faDirectory <> 0 then
  begin
    lbl_Directory.Caption := 'Directory set';
    if not Directory then
      Ergebnis := Ergebnis xor faDirectory;
  end
  else
    lbl_Directory.Caption := 'Directory not set';
  refresh;
  sleep(4000);
  {Reset attributes}
  FileSetAttr('C:\Temp', Ergebnis);
  {Check if attributes were reset correctly}
  Ergebnis := fileGetAttr('C:\Temp');
  if Ergebnis and faHidden <> 0 then
    lbl_hidden.Caption := 'Hidden file'
  else
    lbl_hidden.Caption := 'Not a hidden file';
  if Ergebnis and faDirectory <> 0 then
    lbl_Directory.Caption := 'We have a directory'
  else
    lbl_Directory.Caption := 'There is no directory';
  if Ergebnis and faReadOnly <> 0 then
    lbl_ReadOnly.Caption := 'File is write-protected'
  else
    lbl_ReadOnly.Caption := 'File is not write-protected';
  refresh;
end;

Nincsenek megjegyzések:

Megjegyzés küldése