Using x++ code reading data from csv file format

时间:2021-01-06 16:19:56

The following X++ code is tested in  Dynamics AX 2009 development environment!

Wrote by : Jimmy Nov 24th 2010

static void Jimmy_readCSVFieldFromAXCode(Args _args)
{
    AsciiIo             asciiIo;
    FileIoPermission    perm;
    
    Test                Test;
    
    container           con;
    name                ItemId,Name;
    price               price;
    int                 i;
    
    #define.ExampleFile(@"c:\Book1.csv")
    #define.ExampleOpenMode("r")
    #define.FileDelimiter(",")
;
    // The AsciiIO.new method runs under code access permission.
    if(!WinAPI::fileExists(#ExampleFile))
        return;
    perm = new FileIoPermission(#ExampleFile,#ExampleOpenMode);
    if (perm == null)
        return;
  
    perm.assert();  // Code access permission scope starts here.
   
    asciiIo = new AsciiIo(#ExampleFile,#ExampleOpenMode);
    asciiIo.inFieldDelimiter(#FileDelimiter);
    
    if (asciiIo != null)
    {
        con = asciiIo.read();
        delete_from Test;
        while (asciiIo.status() == IO_Status::Ok)
        {

            ItemId  = conPeek(con,1);
            name    = conPeek(con,2);
            price   = conPeek(con,3);

            i++;
            ttsbegin;
            Test.clear();
            Test.ItemId = ItemId;
            Test.Name   = name;
            Test.Price2 = price;
            Test.doInsert();
            info(strfmt("%1 : %2,%3,%4",i,
                        Test.ItemId,
                        Test.Name,
                        num2str(price,1,2,1,2)));

            ttscommit;
            con = asciiIo.read();
        }
    }
    info(strfmt("total read %1 records [from %2]",i,#ExampleFile));
}