How to: Use Streams to Write to Text Files
The InStream (input stream) and OutStream (output stream) data types are generic stream objects that you can use to read from or write to files. This topic shows you how to use the OutStream object to write to a text file. You create a codeunit to accomplish this task. For information about how to use streams to read text files, see How to: Use Streams to Read from Text Files.
To use a stream to write to a text file
In Object Designer, choose Codeunit, and then choose the New button to open the C/AL Editor.
You declare variables to represent the text file and output stream object that you want to work with.
From the View menu, choose C/AL Globals to open the C/AL Globals window.
Under the Variable tab, in the Name column, declare a variable that represents the text file and then set DataType to File.
Declare a second variable that represents the output stream that will write the data, then set DataType to OutStream.
If you want to retrieve the number of characters that are written to the text file, create variable to hold the value.
From the View menu, choose C/AL Code to open the C/AL Editor.
In the C/AL Editor, in the OnRun() trigger, add code that uses the CREATE Function (File) to create the file that you want to write to. The code will resemble following code snippet:
Use the CREATEOUTSTREAM Function (File) to create the output stream. The code will resemble the following code snippet:
Use the OutStream.WRITETEXT Function to write the data from the output stream to the file. The code will resemble the following code snippet:
From the File menu, choose Save AS.
In the Save As dialog box, in the ID text box, enter an ID for the codeunit.
In the Name text box, enter a name for the codeunit.
Verify that Compile is selected and then choose the Yes button.
The following example shows how to use an output stream to write text to a text file and displays the number of characters that were written to the file. This example requires that you create the following variables in the C/AL Globals window.
MyFile.CREATE('c:\MyNewFolder\MyWriteText.txt'); MyFile.CREATEOUTSTREAM(MyOutStream); NumberOfChars := MyOutStream.WRITETEXT('Hello World!'); MESSAGE('%1 characters were written to the file.', NumberOfChars);