컴퓨터/프로그래밍

라자루스 사용자 AppData 폴더 위치 구하기

2022. 5. 3. 19:04

프로그램을 윈도우 프로그램 폴더에 저장했다면, 권한 문제 대문에 그 위치에 파일을 생성하지 못합니다. 이런 경우 AppData 폴더를 이용합니다. AppData 폴더 위치는 ShGetSpecialFolderPath() 함수에 CSIDL_LOCAL_APPDATA를 인수로 호출하여 구할 수 있습니다. ShGetSpecialFolderPath() 함수를 사용하려면 uses절에 shlobj를 추가해야 합니다.

How to get the appdata folder location in Lazarus

라자루스에서 AppData 폴더 위치를 구하는 예제입니다. Button1을 클릭하면 labAppData에 AppData 폴더 위치를 표시합니다.

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    labAppData: TLabel;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private

  public

  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

uses
  shlobj;

 { TForm1 }

function GetAppDataFolderDir: string;
var
   r: Boolean;
   path: array[0..Max_Path] of Char;
begin
   r := ShGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, False);
   if not r
   then
      raise Exception.Create('Could not find AppData location.') ;
   Result := Path;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  labAppData.Caption := GetAppDataFolderDir;
end;

end.

uses절에 shlobj를 추가하고 ShGetSpecialFolderPath()에 인수 값 CSIDL_LOCAL_APPDATA로 구했습니다.

예제를 실행한 후 Button1을 클릭하면 AppData 폴더의 위치가 표시됩니다.

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    labAppData: TLabel;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private

  public

  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

uses
  shlobj, lazutf8;

 { TForm1 }

function LocalAnsiToUtf8( strAnsi: string): string;
begin
   SetCodePage( RawByteString( strAnsi), 949, FALSE);
   result  := AnsiToUtf8( strAnsi);
end;

function GetAppDataFolderDir: string;
var
   r: Boolean;
   path: array[0..Max_Path] of Char;
begin
   r := ShGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, False);
   if not r
   then
      raise Exception.Create('Could not find AppData location.') ;
   Result := LocalAnsiToUtf8( Path);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  labAppData.Caption := GetAppDataFolderDir;
end;

end.

만일 AppData 폴더 위치에 한글이 있어서 깨진다면 위 예제 코드에서 LocalAnsiToUtf8() 함수를 참고하여 UTF8로 변환합니다. UTF8 관련 함수를 사용하기 위해서는 uses절에 lazutf8 유닛을 추가합니다.