Delphiでパス文字列を結合する関数を作ってみる

Delphiには2つのパス文字列を結合するSystem.IOUtils.TPath.Combine関数がある。

Path := TPath.Combine('C:\alice\bob', 'carol'); 
//=>Pathは'C:\alice\bob\carol'

3つ以上のパス文字列を結合するときは入れ子にする。

Path := TPath.Combine(TPath.Combine('C:\alice\bob', 'carol'), 'dave'); 
//=>Pathは'C:\alice\bob\carol\dave'

関数を入れ子にするよりも、単純に文字列を結合した方が読みやすいかも。

Path := 'C:\alice\bob' + TPath.DirectorySeparatorChar + 'carol' +
  TPath.DirectorySeparatorChar + 'dave';

そこで、複数のパス文字列を結合する関数を作成してみた。

uses System.IOUtils;

type
  TPathHelper = record helper for System.IOUtils.TPath
    class function Combines(const Paths: array of string): string; static;
  end;

class function TPathHelper.Combines(const Paths: array of string): string;
var
  I: Integer;
begin
  if Length(Paths) = 0 then Exit;
  Result := Paths[0];
  for I := 1 to High(Paths) do
    Result := System.IOUtils.TPath.Combine(Result, Paths[i]);
end;

この関数を使うと次のように書くことができる。

Path := TPath.Combines(['C:\alice\bob', 'carol', 'dave']);
//=>Pathは'C:\alice\bob\carol\dave'

もう少し長くなると違いがよくわかるかも。

Path := TPath.GetHomePath + TPath.DirectorySeparatorChar + 'Documents' +
  TPath.DirectorySeparatorChar + 'sample.jpg';

Path := TPath.Combines([TPath.GetHomePath, 'Documents', 'sample.jpg']);

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください