Einzelnen Beitrag anzeigen

mytbo

Registriert seit: 8. Jan 2007
472 Beiträge
 
#4

AW: Beste Methode, um "IsAbsoluteFilePathValid" narrensicher zu implementieren ?

  Alt 14. Sep 2023, 16:58
mir geht es drum, das möglichst erstmal rein am Text des FilePaths auszumachen,
ohne Seiteneffekte und sonstige "Magie", wie zum Beispiel OS-spezifische Funktionen wie "GetFullPathName" von Windows.
So richtig habe ich deine Anforderungen nicht verstanden, vielleicht so:
Delphi-Quellcode:
type
  TFileNameValidation = (fnvDirName, fnvFileName);
  TFileNameValidations = set of TFileNameValidation;

function CheckFileName(const pmcFileName: TFileName; pmValidationParts: TFileNameValidations; pmCheckedFileName: PFileName = Nil): Boolean;
var
  dirName, fileName: TFileName;
begin
  if (pmcFileName = '') or (pmValidationParts = []) then Exit(False); //=>

  Result := True;
  try
    if fnvDirName in pmValidationParts then
    begin
      dirName := TPath.GetDirectoryName(pmcFileName);
      Result := ((dirName <> '') and TPath.IsPathRooted(dirName));
    end;

    if Result
      and (fnvFileName in pmValidationParts) then
    begin
      fileName := TPath.GetFileName(pmcFileName);
      Result := ((fileName <> '') and TPath.HasValidFileNameChars(fileName, False));
    end;

    if Result
      and (pmCheckedFileName <> Nil) then
    begin
      if (dirName <> '') and (fileName <> '') then
        pmCheckedFileName^ := TPath.Combine(dirName, fileName, False)
      else if fileName <> 'then
        pmCheckedFileName^ := fileName
      else
        pmCheckedFileName^ := dirName;
    end;
  except
    Result := False;
  end;
end;

var
  fileName: TFileName;
begin
  fileName := 'C:\Dummy\Test001\Filename.txt';
  // fileName := '/private/var/mobile/Containers/Data/Application/97DD...A/tmp/Temporary.tmp';
  // fileName := '\Test001\Filename.txt';
  // fileName := '/Temporary.tmp';
  // fileName := 'Filename.txt';
  // fileName := 'C:\Dummy\Test001\';
  // fileName := 'Dummy\Test001\Template.txt';

  if CheckFileName(fileName, [fnvDirName, fnvFileName], @fileName) then
    ShowMessage(fileName);
Bis bald...
Thomas
  Mit Zitat antworten Zitat