본문 바로가기

카테고리 없음

[윈도우즈 API] 디렉토리나 파일의 속성(변경/생성/사용한 날짜, 특성) 바꾸기

반응형
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, DateUtils;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// Convert TDateTime to TFileTime.
function DateTimeToFileTime(DateTime: TDateTime): TFileTime;
var
  SystemTime: TSystemTime;
begin
  if (DateTime > 0) then
  begin
    DateTimeToSystemTime(DateTime, SystemTime);
    SystemTimeToFileTime(SystemTime, Result);
    LocalFileTimeToFileTime(Result, Result);
  end
  else
  begin
    Result.dwLowDateTime  := 0;
    Result.dwHighDateTime := 0;
  end;
end;

// Convert TFileTime to TDateTime.
function FileTimeToDateTime(FileTime: TFileTime): TDateTime;
var
  SystemTime  : TSystemTime;
begin
  FileTimeToLocalFileTime(FileTime, FileTime);
  FileTimeToSystemTime(FileTime, SystemTime);
  Result  := SystemTimeToDateTime(SystemTime);
end;

// Convert TFileTime to a Date&Time string.
function FileTimeToDateTimeStr(FileTime : TFileTime): String;
begin
  Result := FormatDateTime(ShortDateFormat + ' hh:mm:ss:zzz', FileTimeToDateTime(FileTime));
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Filename: String;
  FileHandle: THandle;
  FileAttr: TWin32FindData;
begin
  Filename := 'c:\ZZZ'; // 속성을 변경할 디렉토리 path
  //Filename := 'c:\ZZZ\Project1.exe'; // 속성을 변경할 파일 path

  if GetFileAttributesEx(PChar(Filename), GetFileExInfoStandard, @FileAttr) then
  begin
    FileHandle := CreateFile(PChar(Filename),
                             GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE,
                             nil, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH or FILE_FLAG_BACKUP_SEMANTICS, 0);

    try
      // 만든(Created) 날짜 바꾸기
      FileAttr.ftCreationTime := DateTimeToFileTime(EncodeDateTime(2004, 1, 1, 12, 30, 11, 100));
      SetFileTime(FileHandle, @FileAttr.ftCreationTime, nil, nil  );

      // 수정한(Modified) 날짜 바꾸기
      FileAttr.ftLastWriteTime := DateTimeToFileTime(EncodeDateTime(2004, 1, 2, 12, 31, 12, 200));
      SetFileTime(FileHandle, nil, nil, @FileAttr.ftLastWriteTime );

      // 엑세스한(Accessed) 날짜 바꾸기
      FileAttr.ftLastAccessTime := DateTimeToFileTime(EncodeDateTime(2004, 1, 3, 12, 32, 13, 300));
      SetFileTime(FileHandle, nil, @FileAttr.ftLastAccessTime, nil);

      // 속성 바꾸기
      // FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_SYSTEM, FILE_ATTRIBUTE_ARCHIVE
      FileAttr.dwFileAttributes := FileAttr.dwFileAttributes or FILE_ATTRIBUTE_READONLY;
      
      SetFileAttributes(PChar(Filename), FileAttr.dwFileAttributes)
    finally
      CloseHandle(FileHandle);
    end;

    ShowMessage('속성이 변경되었습니다');
  end;  
end;

end.
반응형