TPath.Combine

I guess that everyone already had to solve this small issue. There are two variables, one with a path, the other with the filename and they have to be combined.
In the old Delphi world there is the function IncludeTrailingPathDelimiter from System.SysUtils.

procedure TMyObject.DoSomething;
var
  sFileName: string;
  sPath: string;
begin
  sFileName := 'Datei.txt';
  sPath := 'c:\temp';

  sFileName := IncludeTrailingPathDelimiter(sPath) + sFileName;
  Writeln(sFileName);
end;

With the unit System.IOUtils Delphi offers the new record TPath with the method combine.

procedure TMyObject.DoSomething;
var
  sFileName: string;
  sPath: string;
begin
  sFileName := 'Datei.txt';
  sPath := 'c:\temp';

  sFileName := TPath.Combine(sPath, sFileName);
  Writeln(sFileName);
end;

In our example both functions do the same. But if you look at the implementation of TPath.Combine you can see that it offers some other functionalities. TPath.Combine calls TPath.DoCombine that checks the valid chars and also checks if Path2 is already absolute. This means that the following code raises an exception.

procedure TMyObject.DoSomething;
var
  sFileName: string;
  sPath: string;
begin
  sFileName := 'Datei.txt';
  sPath := 'c:\temp' + #0;

  sFileName := TPath.Combine(sPath, sFileName);
  Writeln(sFileName);
end;

And this code does work.

procedure TMyObject.DoSomething;
var
  sFileName: string;
  sPath: string;
begin
  sFileName := 'c:\temp\Datei.txt';
  sPath := 'c:\temp';

  sFileName := TPath.Combine(sPath, sFileName);
  Writeln(sFileName);
end;
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.