Re: Detect file change
[ Delphi Tutorials -- by DelphiLand ]
Posted by Pramod B R on January 03, 2005 at 09:38:37:
In Reply to: Detect file change posted by james on December 30, 2004 at 03:59:50:
First of all, you can directly use 'lines.LoadFromFile' of memo to load text file into memo. To check if the file has changed, use following api functions (in windows) GetFileTime and CompareFileTime in Timer. A sample code is given below. (pls add a memo and timer to a new form and paste the code. Change the file path to existing text file) ===========^^^^^^^^^^^^^^============== unit UpdateMemoOnFileChange; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShellCtrls, ExtCtrls; type TForm1 = class(TForm) Memo1: TMemo; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); private mFileWTime : PFileTime; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var hFile : Cardinal; begin mFileWTime := AllocMem(SizeOf(mFileWTime)); hFile := CreateFile(PChar('D:\Test\Checking.txt'),GENERIC_READ, FILE_SHARE_READ OR FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); GetFileTime(hFile, mFileWTime, nil, nil); CloseHandle(hFile); memo1.Lines.LoadFromFile('d:\test\checking.txt'); end; procedure TForm1.Timer1Timer(Sender: TObject); var hFile : Cardinal; mFlTm : PFileTime; begin hFile := CreateFile(PChar('D:\Test\Checking.txt'),GENERIC_READ, FILE_SHARE_READ OR FILE_SHARE_WRITE,0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); mFlTm := AllocMem(SizeOf(_FILETIME)); GetFileTime(hFile, nil, nil, mFlTm); CloseHandle(hFile); if CompareFileTime(mFlTm^, mFileWTime^) = 1 then Begin Memo1.Lines.LoadFromFile('D:\Test\Checking.Txt'); End; mFileWTime := mFlTm; end; end. =========== Please note that this code is done in D7 and win2k. Compatibility with other versions of Delphi or windows is not tested. One more point to note is that in D7, a component called TShellChangeNotifier (samples pallete) may be usefull instead of timer
Related Articles and Replies
[ Delphi Tutorials -- by DelphiLand ]
|