Reading from a Text File in X++

I’ve read from and written to text files a few different ways in X++, this is one of them. Nothing special here to see, you can find similar code 1000 different places on the web, I’ll throw in number 1001…


static void readFromFile(Args _args)
{
    TextIo              file;
    FileName            filename = @"\\yourfolder\yourfilename.txt";
    Container           con;
    FileIoPermission    permission;

    str                 val1, val2, val3;

    #File

    int                 x = 0;
    ;

    try
    {
        permission = new FileIOPermission(filename, #io_read);
        permission.assert();

        file = new TextIo(filename, #io_read);

        if (!file)
            throw Exception::Error;

        file.inRecordDelimiter(#delimiterCRLF); // set record delimiter, in this case '\n'
        file.inFieldDelimiter("|"); // set field delimiter, in this case a pipe delimited file

        info("Account# | Latitude | Longitude");

        con = file.read();

        while (file.status() == IO_Status::Ok)
        {
            val1 = conpeek(con, 1);
            val2 = conpeek(con, 2);
            val3 = conpeek(con, 3);

            // do some stuff here
           
            x++; // increment counter

            con = file.read();
        }
    }
    catch
    {
        CodeAccessPermission::revertAssert();
        info("An error was encountered.");
    }

    CodeAccessPermission::revertAssert();

    info(strfmt("%1 records updated.", x));
}