unit uMain;
{$mode objfpc}{$H+}
interface
uses
Windows,
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
SaveDialog1: TSaveDialog;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FFilename: string; // variable to store a destination
procedure BeginWriteTest; // a method to begin test writing
procedure AddLog(const AValue: string); // a method to pump a string into the memo1
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
FFilename := ''; // reset internal variable
end;
procedure TForm1.AddLog(const AValue: string);
begin
Memo1.Lines.Add(AValue); // add a line to memo
end;
// this is the handler for the button
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Clear; // clear the memo
FFilename := ''; // reset internal variable
AddLog('Open Save Dialog'); // write to log (memo1)
if SaveDialog1.Execute then // pop up the save file dialog
FFilename := SaveDialog1.FileName; // export the dialogs choosen destination to internal variable
if (FFilename <> '') then // when variable is not empty go on
BeginWriteTest // start the write method
else
AddLog('Open Save Dialog - canceled.'); // or tell that there was nothing to do
end;
procedure TForm1.BeginWriteTest;
const
OpenMode: array[Boolean] of Word = (fmCreate, fmOpenReadWrite); // my own way of how to open with stream a file
var
fs: TStream; // my internal stream variable
b: boolean; // a boolean variable
begin
AddLog('Destination: ' + FFilename);
AddLog('Inside Write Method.');
b := FileExists(FFilename, False); // test if a file exist or if we need to create a new
try
SetLastError(ERROR_SUCCESS); // reset any formerly error message
AddLog('Try to open a Stream Handle.');
fs := TFileStream.Create(FFilename, OpenMode[b] or fmShareCompat or fmShareExclusive, 0); // open a stream handle for writing, depend on fileexist how it is opened or created
try
AddLog('Stream Handle is open for write.');
AddLog(FFilename + ' - created.');
fs.Position := 0; // just to show how to access the stream
finally
fs.Free; // free the stream and close the handle
AddLog('Stream Handle is closed.');
if DeleteFile(FFilename) then // delete the file again to not leave trash on your drive
AddLog(FFilename + ' - deleted.')
else
AddLog(FFilename + ' - failed to deleted.');
end;
except
AddLog('Failed to open Stream Handle.');
AddLog('Message: ' + SysErrorMessage(GetLastError)); // on any exception do print the operating system message
end;
end;
end.