2005/10/10 | 读取、设置文件日期
类别(语言类学习笔记) | 评论(0) | 阅读(166) | 发表于 01:00
unit unitFrmMain;

interface

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

type
TForm1 = class(TForm)
DateTimePicker1: TDateTimePicker;
DateTimePicker2: TDateTimePicker;
DateTimePicker3: TDateTimePicker;
DateTimePicker4: TDateTimePicker;
OpenDialog1: TOpenDialog;
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}
// 转换文件的时间格式

function CovFileDate(FileDate: _FileTime): TDateTime;
var
Tct: _SystemTime;
Temp: _FileTime;
begin
FileTimeToLocalFileTime(FileDate, Temp);
FileTimeToSystemTime(Temp, Tct);
CovFileDate := SystemTimeToDateTime(Tct);
end;

// 获取文件时间,fn表示目标文件路径和名称,fType为取得日期的类型

function GetFileTime(const fn: string; const fType: Byte): string;
const
Model = 'yyyy/mm/dd,hh:mm:ss'; { 设定时间格式 }
var
Tp: TSearchRec; { 声明Tp为一个查找记录 }


begin
FindFirst(fn, faAnyFile, Tp); { 查找目标文件 }
// 返回文件的创建时间
if fType = 1 then
Result := FormatDateTime(Model, CovFileDate(Tp.FindData.ftCreationTime));
// 返回文件的修改时间
if fType = 2 then
Result := FormatDateTime(Model, CovFileDate(Tp.FindData.ftLastWriteTime));
//返回文件的当前访问时间
if fType = 3 then
Result := FormatDateTime(Model, Now);

FindClose(Tp);
end;

procedure SetFileDateTime(const Tf: string);
{ 设置文件时间,Tf表示目标文件路径和名称 }
var
Dt1, Dt2: Integer;
Fs: TFileStream;
Fct, Flt: TFileTime;
begin
Dt1 := DateTimeToFileDate(
Trunc(Form1.DateTimePicker1.Date) + Frac(Form1.DateTimePicker2.Time));
Dt2 := DateTimeToFileDate(
Trunc(Form1.DateTimePicker3.Date) + Frac(Form1.DateTimePicker4.Time));
// 转换用户输入在DataTimePicker中的信息
try
FS := TFileStream.Create(Tf, fmOpenReadWrite);
try
if DosDateTimeToFileTime(LongRec(DT1).Hi, LongRec(DT1).Lo, Fct) and
LocalFileTimeToFileTime(Fct, Fct) and
DosDateTimeToFileTime(LongRec(DT2).Hi, LongRec(DT2).Lo, Flt) and
LocalFileTimeToFileTime(Flt, Flt)
then
// 设置文件时间属性
SetFileTime(FS.Handle, @Fct, @Flt, @Flt);
finally
begin
FS.Free;
ShowMessage('修改成功');
end;
end;
except
// 因为目标文件正在被使用等原因而导致失败
MessageDlg('日期修改操作失败!',
mtError, [mbOk], 0);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
Memo1.Clear;
Memo1.Lines.Add('文件创建日期:' + GetFileTime(OpenDialog1.FileName, 1));
Memo1.Lines.Add('文件修改日期:' + GetFileTime(OpenDialog1.FileName, 2));
Memo1.Lines.Add('文件访问日期:' + GetFileTime(OpenDialog1.FileName, 3));
end;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
OpenDialog1.Execute;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.Execute then
SetFileDateTime(OpenDialog1.FileName);
end;

end.
0

评论Comments