How to: Use Streams to Read from 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 InStream to read from a text file. For information about how to use streams to write text files, see How to: Use Streams to Write to Text Files. You create a codeunit to accomplish this task.
To use a stream to read from a text file
In Object Designer, choose Codeunit, and then choose the New button to open the C/AL Editor.
On the View menu, choose C/AL Globals.
On the Variables 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 input stream that will read the data and set DataType to Instream.
Declare a third variable that receives the data that is read and set the DataType.
In the C/AL Editor, in the OnRun trigger, add code that uses the OPEN Function (File) to open the file that you want to read from. The code will resemble the following code snippet.
Use the CREATEINSTREAM Function (File) to create the input stream. The code will resemble the following code snippet.
Use the InStream.READTEXT Function to read the data from the stream to a text variable such as a buffer or another object. The code that reads the file to a buffer will resemble the following code snippet.
If you are reading from a BLOB, use the InStream.READ Function to read the BLOB.
After all the content of the file is read, use the CLOSE Function (File) to close the file. The code will resemble the following code snippet.
On the File menu, choose Save to save the new codeunit.
In the Save As window, in the ID text box, enter an ID for the codeunit. In the Name text box, enter a name for the codeunit.
Verify that the Compile field is selected and then choose the Yes button.
The following example reads a file that is named MyText.txt into a buffer and displays the contents of the buffer in a message. The file is read until the end of the file is reached. This example requires that you create the following variables in the C/AL Globals window.
MyFile.OPEN('c:\MyFolder\MyText.txt'); MyFile.CREATEINSTREAM(StreamInTest); WHILE NOT StreamInTest.EOS DO BEGIN StreamInTest.READTEXT(Buffer); // Do some processing. MESSAGE('Stream is still reading: %1', Buffer); END; MyFile.CLOSE; MESSAGE('End of stream is reached.');