Reading and Writing textfile with Encoding

To read and write textfiles, in Dynamics NAV, with special Encoding, you have to use the StreamReader or StreamWriter class, and the Encoding class from .NET.
With this you don’t need your OEM2ANSI conversion functions anymore.
Note that XML Port has encoding built in, and File in the latest versions also offers some simple Encoding options.

Read from file

If you want to read a textfile , you use the .NET StreamReader class.
In this example I am assuming UTF8 encoding.
You have to know that encoding of the file beforehand!

Declare the following variables:
2017-04-19_0727

// Open file
InputFile.Open('C:\temp\test.txt'); 
InputFile.CREATEINSTREAM(FileInStream);
// Create instance of StreamReader, and set the wanted Encoding
StreamReader := StreamReader.StreamReader(FileInStream, Encoding.UTF8); 
// Read entire file to messagebox
MESSAGE(StreamReader.ReadToEnd();
// Close stream and file when done reading
StreamReader.Close();
InputFile.CLOSE();

Write to file

If you want to write a textfile, you use the .NET StreamWriter class.
In this example I am writing the file in Unicode encoding.

Declare the following variables:2017-04-18_0911

// Create file
OutputFile.CREATE('C:\temp\test.txt');
OutputFile.CREATEOUTSTREAM(FileOutStream);
// Create instance of streamwriter, and set Encoding
StreamWriter := StreamWriter.StreamWriter(FileOutStream, Encoding.Unicode); 
// Write lines to file
StreamWriter.WriteLine('First line');
StreamWriter.WriteLine('Second line');
// Close stream and file when done writing
StreamWriter.Close();
OutputFile.CLOSE();

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s