D365FO – AX – Convert a string into a container

Suppose you have a CSV file that contains 100 lines and every line as 5 fields separated by a separator (comma, semicolon, pipe, etc..)

Now you want to retrieve the lines and put every single field into a string.

You can do it by using a container and str2con method

How to do in X++

static void ImportWithStreamReader(Args _args)
   Filename                filename = @'c:\file.txt';           
   System.IO.StreamReader  reader;
   System.String           line;
   InteropPermission       interopPermission;
   container               con;
   str                     field1;
   str                     field2;
   str                     field3;
   interopPermission = new InteropPermission(InteropKind::ClrInterop);
   reader = new System.IO.StreamReader(filename,
   //First line is the header
   line = reader.ReadLine();
   while (!System.String::IsNullOrEmpty(line))
       line = reader.ReadLine(); //the file line contains 3 fields separated by semicolon ";"
       con = str2con(line,';'); //use str2con to split the fields into 3 string variables (field1, field2, field3, field4)
       field1 = conpeek(con,1);
       field2 = conpeek(con,2);
       field3 = conpeek(con,3);
       field4 = conpeek(con,4);

This is the structure of the text file

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 )

Connecting to %s