Windows、システム、テンポラリフォルダの取得

Windows、システム、テンポラリの各フォルダを取得する関数を、Delphiのネイティブな文字列型で呼び出せる形の関数にします。ただし、関数名は既存のAPIと同じ名前を使用しているので注意が必要です。APIの方を呼び出すにはWindowsユニットから書く必要があります。
難しい処理はまったくないでしょう。ただ、文字列を受け取るのに必要なバッファサイズをMAX_PATHなどで確保せずに、APIを****(nil, 0)の形で呼び出して取得しています。(GetTempPathは (0, nil) 引数の順番に規則性がないのがMSらしい(苦笑))必要最低限のバッファサイズを割り当てるので効率がいいです。

function GetWindowsDirectory(var S: String): Boolean;
//Windowsディレクトリを取得
var
  Len: Integer;
begin
  //文字列を格納するのに必要なサイズを取得
  Len := Windows.GetWindowsDirectory(nil, 0);
  if Len > 0 then
  begin
    SetLength(S, Len);//バッファ割り当て
    Len := Windows.GetWindowsDirectory(PChar(S), Len);
    SetLength(S, Len);//サイズ調節を行う
    Result := Len > 0;
  end else
    Result := False;
end;


function GetSystemDirectory(var S: String): Boolean;
//システムディレクトリを取得
var
  Len: Integer;
begin
  //文字列を格納するのに必要なサイズを取得
  Len := Windows.GetSystemDirectory(nil, 0);
  if Len > 0 then
  begin
    SetLength(S, Len);//バッファ割り当て
    Len := Windows.GetSystemDirectory(PChar(S), Len);
    SetLength(S, Len);//サイズ調節を行う
    Result := Len > 0;
  end else
    Result := False;
end;


function GetTempPath(var S: String): Boolean;
//テンポラリディレクトリを取得
var
  Len: Integer;
begin
  //文字列を格納するのに必要なサイズを取得
  Len := Windows.GetTempPath(0, nil);
  if Len > 0 then
  begin
    SetLength(S, Len);//バッファ割り当て
    Len := Windows.GetTempPath(Len, PChar(S));
    SetLength(S, Len);//サイズ調節を行う
    Result := Len > 0;
  end else
    Result := False;
end;

Copyright 2001 Rinka Kouzuki All Rights Reserved.