How to read text file in Dynamics 365 F&O

Using System.IO.Stream library you can read text files. here is a runnable class to load the file using FileUploadBuild control, then read its content:

class AZTxtFileRead
{
/// /// Runs the class with the specified arguments. ///
/// The specified arguments.
public static void main(Args _args)
{
#File;
    
    System.IO.Stream            stream;
    FileUploadBuild             fileUpload;
    DialogGroup                 dlgUploadGroup;
    FileUploadBuild             fileUploadBuild;
    FormBuildControl            formBuildControl;
    Dialog                      dialog = new Dialog("Import the data from File");

    dlgUploadGroup          = dialog.addGroup("@SYS54759");
    formBuildControl        = dialog.formBuildDesign().control(dlgUploadGroup.name());
    fileUploadBuild         = formBuildControl.addControlEx(classstr(FileUpload), 'Upload');
    fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);
    fileUploadBuild.fileTypesAccepted('.txt');

    if (dialog.run() && dialog.closedOk())
    {
        FileUpload fileUploadControl     = dialog.formRun().control(dialog.formRun().controlId('Upload'));
        FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();

        if (fileUploadResult && fileUploadResult.getUploadStatus())
        {
            CommaTextStreamIo textStream = CommaTextStreamIo::constructForRead(File::UseFileFromURL(fileUploadResult.getDownloadUrl()));

            textStream.inFieldDelimiter(',');
            textStream.inRecordDelimiter(#delimiterCRLF);

            // First line might have header information
            container currentLine = textStream.read(); 

            while(currentLine)
            {

                info(strFmt("%1, %2, %3", 
                    conPeek(currentLine, 1),
                    conPeek(currentLine, 2),
                    conPeek(currentLine, 3)));

                currentLine = textStream.read();

            }
        }

    }
}
}

Published by

Unknown's avatar

Abdallah Zein Al Abdin

I have been working with Dynamics 365 For Finance & Operations (aka Dynamics AX) since 2008. Currently I work for Microsoft as Principal Consultant.

Leave a comment