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);
   interopPermission.assert();
 
   reader = new System.IO.StreamReader(filename,
   System.Text.Encoding::get_UTF8());
   //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);
   }
 
   reader.Close();
   reader.Dispose();
}

This is the structure of the text file

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...