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:

// Open file
// Create instance of StreamReader, and set the wanted Encoding
StreamReader := StreamReader.StreamReader(FileInStream, Encoding.UTF8); 
// Read entire file to messagebox
// Close stream and file when done reading

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
// 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


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s