Appending to the end of a file - BC v14, C/AL

mark02tjmark02tj Member Posts: 5
Hello - I am trying to append lines to an existing file in BC v14 (although this could pertain to NAV 2018 as well). I am opening/creating a file as shown below:

TempFileName := FileMgt.ServerTempFileName('txt');
OutputFile.WRITEMODE := TRUE;
OutputFile.TEXTMODE := TRUE;
IF EXISTS(TempFileName) THEN
OutputFile.OPEN(TempFileName)
ELSE OutputFile.CREATE(TempFileName);
OutputFile.CREATEOUTSTREAM(OutputFileStream);
Encoding := Encoding.ASCII;
StreamWriter := StreamWriter.StreamWriter(OutputFileStream, Encoding);

Note: this seems to be pretty common code and if I remember correctly, I found this on Microsoft's site several years ago.

This code works well and to populate the file, I use "Streamwriter.WriteLine(FileString)". Eventually I close the file after the last line is written.


Currently I have a project where I want to open a file that I've previously created and append more lines to the end of the file. Is there an easy way to do this in C/AL?

When searching online for an answer, I've seen some posts that indicate that you might be able to do this by first reading the existing file, re-outputting the existing contents back to the file and then writing more lines to the file. There are two issues with this approach - First, I'm not sure how to do it. :smile: Next, the file has the potential to become many thousands of lines long and I'm not sure how long it would take to read and rewrite a 30,000 line file. Hence the reason for me asking if there's an "easy way" to accomplish this. Also, this is kind of a one-time thing. Once this large file is created, we won't be creating it again so I'm trying to minimize the development time, while also trying to avoid creating several hundred smaller files and copy/pasting them all into a larger file.

THANKS!!

Answers

  • vaprogvaprog Member Posts: 1,155
    You cannot do this with C/AL streams, as there is no way to position them. Since you have a file (not a Blob) you can use FILE:
    // upload your existing file to the server and get that file's full filename
    OutputFile.WRITEMODE := TRUE;
    OutputFile.TEXTMODE := TRUE;
    OutputFile.OPEN(TempFileName, TEXTENCODING::MSDos);
    OutputFile.SEEK(OutputFile.LEN);
    OutputFile.WRITE(FileString);
    OutputFile.CLOSE;
    // download the file again
    

    I don't know if you could use .NET streams. Check out codeunits 3034 DotNet_Stream, and 3025 DotNet_StreamWriter.
Sign In or Register to comment.