How to save/read external text files?

This script illustrates how to write data to a text file and read the contents of a text file.

How to save the contents of a form to a text file when the form is submitted?

This example works only in a HTML Viewer publication as we use the "OnFormSubmit" event of the UserMain script.

First step: write the script

go to the Script Manager, double click on "UserMain" and copy/paste all of the following text:

procedure WriteTextToFile(Filename, Contents: String);
var
T: TStringList;
begin
T := TStringList.Create;
// Sets the contents.
T.Text := Contents;
// Saves the file.
T.SaveToFile(Filename);
 T.Free;
end;

procedure WriteText;
var
S, S2: String;
begin
// A simple function to test the function.
// Finds a name for our text file.
// a) Gets the path to the folder where to save the file.
S := GetGlobalVar("HEPubStorageLocation", "");
if S = "" then exit;
// b) Appends the filename
S := IncludeTrailingBackslash(S) + "testfile.txt";
// Then obtains the form contents.
S2 := GetFormContents;
// Calls our procedure to output a text file.
if S2 <> "" then WriteTextToFile(S, S2);
end;


function OnFormSubmit(Action, Method: String): Boolean;
begin
// When a form is submitted by the user (HTML Viewer only)
WriteText;
// Set Result to True if you do not want the viewer to handle the form action itself.
Result := False;
end;

Be sure to remove the existing OnFormSubmit event and replace it with the one shown above before you continue.

How does it work?

When you submit a form, the HTML viewer will trigger the OnFormSubmit event. As you can see, we call the WriteText procedure: the latter will find a name for the text file (using the global variable "HEPubStorageLocation" which ensures us that we have a folder where we can write files), read the contents of the form thanks to GetFormContents and finally write the contents of the text file.

The WriteTextToFile is a general function that you can use in any of your publication. It uses an internal object TStringList to create the text file.

How to read data from a text file?

You can use this general function to get the entire contents of an existing text file:

function ReadTextFile(Filename: String): String;
var
T: TStringList;
begin
T := TStringList.Create;
// Loads the text file.
T.LoadFromFile(Filename);
// Gets the contents.
Result := T.Text;
 T.Free;
end;

The TStringList object is an interesting object to manipulate text data and text files: for more information about how to use it, please go to this page:
http://www.delphibasics.co.uk/RTL.asp?Name=TStringList

Introduction to Scripting

Using the Script Manager

Script Function Reference