記事カテゴリ

ユーザー機能


 2024年4月16日(火) 21:55 JST

[Delphi] ファイル情報を取得する

  • 投稿者:
  • 表示回数
    10,676

以下のサンプルコードを参考にしてください。
このサンプルアプリケーションは、どのようにしてファイル、フォルダ、ドライブの情報を取得するかを提供しています。

サンプルプログラムのダウンロードは→[Delphi FAQ用サンプル] ファイル情報を取得する

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ShellApi, FileCtrl;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Edit1: TEdit;
    Label2: TLabel;
    Edit2: TEdit;
    Label3: TLabel;
    Edit3: TEdit;
    Label4: TLabel;
    FileListBox1: TFileListBox;
    DirectoryListBox1: TDirectoryListBox;
    DriveComboBox1: TDriveComboBox;
    Label5: TLabel;
    Edit4: TEdit;
    Edit5: TEdit;
    Label6: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure FormPaint(Sender: TObject);
  private
  public
  end;

var 
 Form1: TForm1;
 FileInfo: SHFILEINFO; 

implementation 

{$R *.DFM} 

procedure TForm1.Button1Click(Sender: TObject); 
var
  Filename: String;
  attrs: string;
  attributes: integer;
begin 
  Form1.Repaint;
  if (filelistbox1.ItemIndex <> - 1) then
  begin 
    Filename := FileListBox1.FileName; 
  end 
  else 
  begin
    Filename := DirectoryListBox1.Directory; 
  end; 
  Edit1.Text := filename; 
  // 表示名の取得
  SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo), SHGFI_DISPLAYNAME);
  Edit2.Text := FileInfo.szDisplayName; 
  // ファイル種別の取得
  SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo), SHGFI_TYPENAME);
  Edit3.Text := FileInfo.szTypeName; 
  // ファイルに関連づいたアイコンの取得
  SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo), SHGFI_ICON);
  Drawicon(canvas.handle,5,170,FileInfo.hIcon);
  Form1.Repaint; 
  // ファイル属性の取得
  attributes := GetFileAttributes(PChar(FileName));
  attrs := '';
  if Bool(attributes and FILE_ATTRIBUTE_READONLY) then attrs := attrs + 'R';
  if Bool(attributes and FILE_ATTRIBUTE_HIDDEN) then attrs := attrs + 'H';
  if Bool(attributes and FILE_ATTRIBUTE_SYSTEM) then attrs := attrs + 'S';
  if Bool(attributes and FILE_ATTRIBUTE_ARCHIVE) then attrs := attrs + 'A';
  Edit4.text := attrs;
  // 最終更新日付の取得
  try
    edit5.text := DateTimeToStr(FileDateToDateTime(FileAge(FileName)));
  except
    // ファイルが選択されていない場合(フォルダやドライブの場合)
    on EConvertError do edit5.text := 'Not Available'; 
  end; 
end;

procedure TForm1.FormPaint(Sender: TObject); 
begin 
  // アイコンの再描画(画面外にフォームが出た場合など)
  Drawicon(canvas.handle, 5, 170, FileInfo.hIcon);
end; 
end.

トラックバック

このエントリのトラックバックURL:
https://www.blackcat.xyz/trackback.php/ProgramingFAQ_del0020

以下のコメントは、その投稿者が所有するものでサイト管理者はコメントに関する責任を負いません。