Tuesday, November 29, 2011

How to read a CSV , txt file in AX 2009

Hi Folks,


In this post, I am going to explain you on how to read a CSV file in AX 2009.


1. First of all, make sure that the file is accessible and has sufficient permissions to read the file.


2. Now follow the below code which reads the file, reads all the lines in the file and inserts into the table.


#File
CommaIo                 aSCIIFile;
Container                  recordsCon;
FileIoPermission perm;
StudentTable studentTable;
#define.ExampleFile(@"c:\test.txt")
;

perm = new FileIoPermission(#ExampleFile, #io_read);

if (perm == null)
{
       return;
}
// Grants permission to execute the CommaIo.new method.
    // CommaIo.new runs under code access security.
    perm.assert();
 
// BP deviation documented.


aSCIIFile = new CommaIo(#ExampleFile,#io_read);
ttsbegin;
while (aSCIIFile.status()== IO_Status::Ok) //Reading the ASCII file if records are there
{
               recordsCon     = aSCIIFile.read();
               for(j=1;j<=Conlen(recordsCon);j++)
              {
                               studentTable.(fieldName2Id(tableNum(studentTable), "Id")) = conpeek(recordsCon,j);
              }
              studentTable.insert();
}
ttscommit;

No comments: