Tip #30 | Reading 1000 + Characters from a File

This Blog Article was brought forward from my old blog

UPDATE 2014 : In current versions with DotNet interop you would probably want to use that instead.

As many of you know there is a lenght limitation of text variables in Microsoft Dynamics NAV.

One of the real-life problems you can encounter due to this is when doing interfacing, especially when reading EDI files.

EDI files are often very long and without Cariage Return Line Feeds.

Solutions are using a dataport with a delimiter such as ‘+’ instead of NewLine or asking the EDI vendor to implement CRLF’s.

If both are not possible, for example if you want to read the EDI files though a NAS you have to use a codeunit with File variable.

Using the File variable with long textlines with result in overflow errors.

The solution to work around this is using a stream variable. This is how:

i := 1;

EDIFile.TEXTMODE(FALSE); EDIFile.OPEN(NewFileName); EDIFile.CREATEINSTREAM(EDIInStream); WHILE NOT EDIInStream.EOS DO BEGIN   EDIProcBufferTemp.”Entry No.” := i;   i := i + 1;   EDIInStream.READTEXT(EDIProcBufferTemp.”EDI Text”, 250);   EDIProcBufferTemp.INSERT; END;

EDIProcBufferTemp.FINDFIRST; EDIText :=  EDIProcBufferTemp.”EDI Text”;

WHILE NOT Finished DO BEGIN   IF STRPOS(EDIText, ‘+’) = 0 THEN BEGIN     EDIProcBufferTemp.DELETE;     IF EDIProcBufferTemp.FINDFIRST THEN       EDIText := EDIText + EDIProcBufferTemp.”EDI Text”     ELSE       Finished := TRUE;   END;     IF STRPOS(EDIText, ‘+’) <> 0 THEN BEGIN     EDITag := COPYSTR(EDIText, 1, STRPOS(EDIText, ‘+’) – 1);     EDIText := COPYSTR(EDIText, STRPOS(EDIText, ‘+’) + 1, 1000);     SplitInfo(EDITag);   END ELSE     SplitInfo(EDIText);  //* Last Tag END;

In this example I move the contents of the textfile to a InSteam variable. The Insteam variable supports the ReadText method that allows us to read the content in smaller chunks.

Then I move the lines into a buffer table for easier processing. (I love working with buffer tables, they make cleaner coding).

Since breaking the file into 250 characters might actualy split some of the EDI tags, I re-connect the lines into a larger text varible. I can easily merge two 250 character lines into one 1000 character variable.

Remember to also process the last tag when there are no more delimiters.

Here you are, good luck.

If you want to learn more about interfacing you can read chapter 9 of my book which is dedicated to this subject.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s